mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 03:46:29 -05:00
* 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>
513 lines
22 KiB
Python
513 lines
22 KiB
Python
import asyncio
|
|
from http import HTTPStatus
|
|
|
|
from sanic import Request, response, Blueprint
|
|
from sanic_ext import validate
|
|
from sanic_ext.extensions.openapi import openapi
|
|
|
|
from modules.map import climatology, export, export_job, lib, quads, schema, search, species_search, winds
|
|
from modules.map.species import GROUP_NAMES
|
|
from modules.map.nuclear import TargetsChanged, get_map_nuclear_config
|
|
from modules.map.pins import get_map_pins_config
|
|
from modules.map.sheet import legend_as_sent
|
|
from wrolpi.api_utils import json_response
|
|
from wrolpi.common import wrol_mode_check
|
|
from wrolpi.events import Events
|
|
|
|
map_bp = Blueprint('Map', '/api/map')
|
|
|
|
|
|
@map_bp.get('/files')
|
|
@openapi.description('List available PMTiles map files')
|
|
def get_files(_: Request):
|
|
files = lib.get_pmtiles_files()
|
|
return json_response(dict(files=files), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.delete('/files/<filename:path>')
|
|
@openapi.description('Delete a PMTiles map file')
|
|
@wrol_mode_check
|
|
async def delete_file(_: Request, filename: str):
|
|
try:
|
|
deleted = lib.delete_pmtiles_file(filename)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
|
|
if deleted:
|
|
return response.empty()
|
|
return response.json({'error': 'File not found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.post('/files/visible')
|
|
@openapi.description('Show a PMTiles map file on the map, or ignore it')
|
|
@validate(schema.MapFileVisibleRequest)
|
|
@wrol_mode_check
|
|
async def post_file_visible(_: Request, body: schema.MapFileVisibleRequest):
|
|
try:
|
|
found = lib.set_pmtiles_file_visible(body.map_path, body.visible)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
|
|
if found:
|
|
return response.empty()
|
|
return response.json({'error': 'File not found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.get('/subscribe')
|
|
@openapi.description('Get map catalog and current subscriptions')
|
|
def get_subscriptions(request: Request):
|
|
catalog = lib.get_map_catalog()
|
|
subscriptions = lib.get_map_subscriptions(request.ctx.session)
|
|
return json_response(dict(catalog=catalog, subscriptions=subscriptions), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.post('/subscribe')
|
|
@openapi.description('Subscribe to a map region for automatic downloads')
|
|
@validate(schema.MapSubscribeRequest)
|
|
@wrol_mode_check
|
|
async def post_subscribe(request: Request, body: schema.MapSubscribeRequest):
|
|
try:
|
|
with request.ctx.db.write() as session:
|
|
await lib.subscribe(session, body.name, body.region)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
|
|
Events.send_created(f'Map subscription created for {body.name}')
|
|
return response.empty(HTTPStatus.CREATED)
|
|
|
|
|
|
@map_bp.delete('/subscribe/<region:str>')
|
|
@openapi.description('Unsubscribe from a map region')
|
|
@wrol_mode_check
|
|
async def delete_subscription(request: Request, region: str):
|
|
try:
|
|
with request.ctx.db.write() as session:
|
|
await lib.unsubscribe(session, region)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.NOT_FOUND)
|
|
|
|
return response.empty(HTTPStatus.NO_CONTENT)
|
|
|
|
|
|
@map_bp.get('/species/subscribe')
|
|
@openapi.description('Get the species pack catalog, subscriptions, and downloaded packs')
|
|
def get_species_subscriptions(request: Request):
|
|
return json_response(dict(
|
|
catalog=lib.get_species_catalog(),
|
|
subscriptions=lib.get_species_subscriptions(request.ctx.session),
|
|
files=lib.get_species_files(),
|
|
), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.post('/species/subscribe')
|
|
@openapi.description("Subscribe to a region's species pack")
|
|
@validate(schema.SpeciesSubscribeRequest)
|
|
@wrol_mode_check
|
|
async def post_species_subscribe(request: Request, body: schema.SpeciesSubscribeRequest):
|
|
try:
|
|
with request.ctx.db.write() as session:
|
|
await lib.species_subscribe(session, body.region)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
|
|
Events.send_created(f'Species subscription created for {body.region}')
|
|
return response.empty(HTTPStatus.CREATED)
|
|
|
|
|
|
@map_bp.delete('/species/subscribe/<region:str>')
|
|
@openapi.description("Unsubscribe from a region's species pack; a downloaded pack is kept")
|
|
@wrol_mode_check
|
|
async def delete_species_subscription(request: Request, region: str):
|
|
try:
|
|
with request.ctx.db.write() as session:
|
|
await lib.species_unsubscribe(session, region)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.NOT_FOUND)
|
|
|
|
return response.empty(HTTPStatus.NO_CONTENT)
|
|
|
|
|
|
@map_bp.delete('/species/files/<region:str>')
|
|
@openapi.description("Delete a region's downloaded species pack")
|
|
@wrol_mode_check
|
|
async def delete_species_files(request: Request, region: str):
|
|
if lib.delete_species_files(region):
|
|
return response.empty()
|
|
return response.json({'error': 'No species pack for that region'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.get('/species')
|
|
@openapi.description('Search the downloaded species by name (q), and/or what lives near a point (lat, lon, radius_km)')
|
|
async def get_species_search(request: Request):
|
|
args = request.args
|
|
try:
|
|
lat = float(args['lat'][0]) if 'lat' in args else None
|
|
lon = float(args['lon'][0]) if 'lon' in args else None
|
|
radius_km = float(args.get('radius_km', species_search.DEFAULT_RADIUS_KM))
|
|
group = int(args['group'][0]) if 'group' in args else None
|
|
limit = int(args.get('limit', species_search.DEFAULT_LIMIT))
|
|
except (ValueError, TypeError):
|
|
return json_response({'error': 'Invalid query parameters'}, HTTPStatus.BAD_REQUEST)
|
|
if (lat is None) != (lon is None):
|
|
return json_response({'error': 'lat and lon must be given together'}, HTTPStatus.BAD_REQUEST)
|
|
if lat is not None and not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
|
return json_response({'error': 'lat or lon is out of range'}, HTTPStatus.BAD_REQUEST)
|
|
if not 0 < radius_km <= species_search.MAX_RADIUS_KM:
|
|
return json_response({'error': f'radius_km must be from 0 to {species_search.MAX_RADIUS_KM}'},
|
|
HTTPStatus.BAD_REQUEST)
|
|
if not 0 < limit <= 500:
|
|
return json_response({'error': 'limit must be from 1 to 500'}, HTTPStatus.BAD_REQUEST)
|
|
|
|
species = await asyncio.to_thread(species_search.search_species, args.get('q', '').strip() or None, lat, lon,
|
|
radius_km, group, limit)
|
|
return json_response(dict(
|
|
species=species,
|
|
packs=len(lib.get_species_files()),
|
|
groups=[dict(code=code, name=name) for code, name in sorted(GROUP_NAMES.items())],
|
|
), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/species/here')
|
|
@openapi.description('What was seen in the ~11 km square containing lat, lon: the species most seen there first')
|
|
async def get_species_here(request: Request):
|
|
try:
|
|
lat, lon = float(request.args['lat'][0]), float(request.args['lon'][0])
|
|
limit = int(request.args.get('limit', species_search.DEFAULT_LIMIT))
|
|
taxon_id = int(request.args['taxon_id'][0]) if 'taxon_id' in request.args else None
|
|
except (KeyError, ValueError, TypeError):
|
|
return json_response({'error': 'lat and lon are required'}, HTTPStatus.BAD_REQUEST)
|
|
if not (-90 <= lat <= 90 and -180 <= lon <= 180) or not 0 < limit <= 500:
|
|
return json_response({'error': 'Invalid query parameters'}, HTTPStatus.BAD_REQUEST)
|
|
here = await asyncio.to_thread(species_search.species_here, lat, lon, limit, taxon_id)
|
|
return json_response(here, HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/species/<taxon_id:int>')
|
|
@openapi.description("A species' details, and where to read about it in Wikipedia")
|
|
async def get_species(request: Request, taxon_id: int):
|
|
species = await asyncio.to_thread(species_search.get_species, taxon_id)
|
|
if not species:
|
|
return json_response({'error': 'Unknown species'}, HTTPStatus.NOT_FOUND)
|
|
species['wikipedia'] = await species_search.find_wikipedia_article(
|
|
request.ctx.session, species['wiki_title'], species['name'])
|
|
return json_response(species, HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/species/<taxon_id:int>/range')
|
|
@openapi.description("A species' range: the cells (as differences) of grid=low (0.1°, every observation) or high "
|
|
"(0.02°, precise ones)")
|
|
async def get_species_range(request: Request, taxon_id: int):
|
|
grid = request.args.get('grid', 'low')
|
|
if grid not in ('low', 'high'):
|
|
return json_response({'error': 'grid must be low or high'}, HTTPStatus.BAD_REQUEST)
|
|
cells = await asyncio.to_thread(species_search.get_species_range, taxon_id, grid)
|
|
if cells is None:
|
|
return json_response({'error': 'Unknown species'}, HTTPStatus.NOT_FOUND)
|
|
return response.json(cells)
|
|
|
|
|
|
@map_bp.get('/pins')
|
|
@openapi.description('Get all map pins')
|
|
def get_pins(_: Request):
|
|
pins = get_map_pins_config().pins
|
|
return json_response(dict(pins=pins), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.post('/pins')
|
|
@openapi.description('Add a map pin')
|
|
@validate(schema.MapPinRequest)
|
|
async def add_pin(_: Request, body: schema.MapPinRequest):
|
|
pin = get_map_pins_config().add_pin(body.lat, body.lon, body.label, body.color)
|
|
return json_response(dict(pin=pin), HTTPStatus.CREATED)
|
|
|
|
|
|
@map_bp.delete('/pins/<pin_id:int>')
|
|
@openapi.description('Delete a map pin by ID')
|
|
async def delete_pin(_: Request, pin_id: int):
|
|
if get_map_pins_config().delete_pin(pin_id):
|
|
return response.empty(HTTPStatus.NO_CONTENT)
|
|
return response.json({'error': 'Pin not found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.put('/pins/<pin_id:int>')
|
|
@openapi.description('Update a map pin by ID')
|
|
@validate(schema.MapPinUpdateRequest)
|
|
async def update_pin(_: Request, pin_id: int, body: schema.MapPinUpdateRequest):
|
|
if get_map_pins_config().update_pin(pin_id, body.label, body.color):
|
|
return response.empty(HTTPStatus.NO_CONTENT)
|
|
return response.json({'error': 'Pin not found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.get('/nuclear/targets')
|
|
@openapi.description('Get the saved nuclear targets')
|
|
def get_targets(_: Request):
|
|
return json_response(dict(targets=get_map_nuclear_config().targets), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.put('/nuclear/targets')
|
|
@openapi.description('Save the nuclear targets: the ones given replace the saved ones, which must be those loaded')
|
|
@validate(schema.MapTargetsRequest)
|
|
async def put_targets(_: Request, body: schema.MapTargetsRequest):
|
|
try:
|
|
targets = get_map_nuclear_config().replace_targets(body.targets, body.loaded_ids)
|
|
except TargetsChanged as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.CONFLICT)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
return json_response(dict(targets=targets), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.delete('/nuclear/targets/<target_id:int>')
|
|
@openapi.description('Delete a saved nuclear target by ID')
|
|
async def delete_target(_: Request, target_id: int):
|
|
if get_map_nuclear_config().delete_target(target_id):
|
|
return response.empty(HTTPStatus.NO_CONTENT)
|
|
return response.json({'error': 'Target not found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.get('/search')
|
|
@openapi.description('Search for places in map search indexes')
|
|
async def search_places(request: Request):
|
|
q = request.args.get('q', '')
|
|
if not q or len(q.strip()) < 1:
|
|
return json_response({'error': 'Query parameter "q" is required'}, HTTPStatus.BAD_REQUEST)
|
|
|
|
try:
|
|
limit = int(request.args.get('limit', 12))
|
|
offset = int(request.args.get('offset', 0))
|
|
lat = float(request.args.get('lat')) if request.args.get('lat') is not None else None
|
|
lon = float(request.args.get('lon')) if request.args.get('lon') is not None else None
|
|
except (ValueError, TypeError):
|
|
return json_response({'error': 'Invalid query parameters'}, HTTPStatus.BAD_REQUEST)
|
|
|
|
data = search.search_places(q.strip(), limit=limit, offset=offset, lat=lat, lon=lon)
|
|
return json_response(data, HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/search/estimate')
|
|
@openapi.description('Get estimated count of map search results')
|
|
async def get_search_estimate(request: Request):
|
|
q = request.args.get('q', '')
|
|
if not q or len(q.strip()) < 1:
|
|
return json_response({'map_places': 0}, HTTPStatus.OK)
|
|
count = search.search_places_count(q.strip())
|
|
return json_response({'map_places': count}, HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/search/status')
|
|
@openapi.description('Get status of map search indexes')
|
|
async def get_search_status(_: Request):
|
|
status = search.get_search_status()
|
|
return json_response(status, HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.post('/search/rebuild')
|
|
@openapi.description('Rebuild all map search indexes')
|
|
@wrol_mode_check
|
|
async def rebuild_search_indexes(_: Request):
|
|
started = search.rebuild_all_search_indexes()
|
|
if started:
|
|
return json_response({'message': 'Search index rebuild started'}, HTTPStatus.ACCEPTED)
|
|
return json_response({'error': 'No PMTiles files found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.post('/search/rebuild/<filename:path>')
|
|
@openapi.description('Rebuild search index for a single PMTiles file')
|
|
@wrol_mode_check
|
|
async def rebuild_single_search_index(_: Request, filename: str):
|
|
try:
|
|
started = search.rebuild_search_index(filename)
|
|
except ValueError as e:
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
|
|
if started:
|
|
return json_response({'message': f'Search index rebuild started for {filename}'}, HTTPStatus.ACCEPTED)
|
|
return json_response({'error': 'File not found'}, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@map_bp.get('/quad')
|
|
@openapi.description('The name of the USGS quadrangle of an area of the map')
|
|
async def get_quad(request: Request):
|
|
"""What the USGS calls the quadrangle between `west`, `south`, `east` and `north` (degrees): `quad` is its
|
|
`name`, its `state`, and whether it is `exact`ly that area (and not a larger quadrangle which has the middle
|
|
of it); or null where there is no name, which is most of the world."""
|
|
try:
|
|
west, south, east, north = (float(request.args.get(i)) for i in ('west', 'south', 'east', 'north'))
|
|
except (TypeError, ValueError):
|
|
return response.json({'error': 'The edges of the area are four numbers'}, HTTPStatus.BAD_REQUEST)
|
|
if not (-180 <= west < east <= 180 and -90 <= south < north <= 90):
|
|
# Not so of a number which is not one, either.
|
|
return response.json({'error': 'The edges are not those of an area of the map'}, HTTPStatus.BAD_REQUEST)
|
|
# The index is read from its file the first time, which is not for the event loop.
|
|
name = await asyncio.to_thread(quads.quad_name, west, south, east, north)
|
|
return json_response({'quad': name.__json__() if name else None})
|
|
|
|
|
|
# How much may be written on the sheet of an exported map.
|
|
SHEET_TEXT_LENGTH = 300
|
|
SHEET_CREDITS = 40
|
|
|
|
|
|
def _export_text(value) -> str:
|
|
"""What was sent as text of an exported map (its title, the name of a layer), as it can be written in a PDF:
|
|
no longer than a line of a sheet, and with nothing in it which is not a character."""
|
|
text = str(value or '').replace('\x00', '')
|
|
return text.encode('utf-8', 'replace').decode('utf-8')[:SHEET_TEXT_LENGTH]
|
|
|
|
|
|
def _sheet_contours(contours) -> dict:
|
|
"""How far apart the contour lines of a map are, as the browser says it, for `export.Sheet`. A map with no
|
|
contour lines says nothing; what is said is written on the sheet only when it is an interval (see
|
|
`modules.map.sheet`)."""
|
|
if not isinstance(contours, dict):
|
|
return {}
|
|
interval = contours.get('interval')
|
|
if isinstance(interval, bool) or not isinstance(interval, (int, float)):
|
|
return {}
|
|
return dict(contour_interval=float(interval), contour_unit=str(contours.get('unit') or '')[:SHEET_TEXT_LENGTH])
|
|
|
|
|
|
def _export_error(e: Exception):
|
|
"""The response for an export which could not go on."""
|
|
if isinstance(e, export_job.ExportNotFound):
|
|
return response.json({'error': str(e)}, HTTPStatus.NOT_FOUND)
|
|
if isinstance(e, export_job.ExportNotReady):
|
|
return response.json({'error': str(e)}, HTTPStatus.CONFLICT)
|
|
if isinstance(e, export_job.ExportStorageError):
|
|
return response.json({'error': str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
|
|
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
|
|
|
|
|
EXPORT_ERRORS = (export.InvalidExport, export_job.ExportNotFound, export_job.ExportNotReady,
|
|
export_job.ExportStorageError)
|
|
|
|
|
|
@map_bp.post('/export')
|
|
@openapi.description('Begin the export of a map as a PDF')
|
|
async def post_export(request: Request):
|
|
"""The browser draws the map, one image for each layer; the API puts them in a PDF, each in a layer of its own.
|
|
That takes a minute or two on a Raspberry Pi, so it is a Job:
|
|
|
|
1. This request describes the map, and is answered with an `export_id`.
|
|
2. `POST /api/map/export/<export_id>/layer/<index>` sends the image of each layer.
|
|
3. `POST /api/map/export/<export_id>/start` is answered with a `job_id`, to watch at `/api/jobs/<job_id>`.
|
|
4. `GET /api/map/export/<export_id>/pdf` is the PDF, once the Job is complete.
|
|
|
|
`DELETE /api/map/export/<export_id>` stops an export at any of those steps, and removes what was sent.
|
|
|
|
The JSON body: `width` and `height` in pixels, `dpi`, `title`, `layers`: the name of each image from the bottom
|
|
up (images of one name are one layer of the PDF), `bounds`: the west, south, east and north edges of the images in degrees, with which the PDF says where it
|
|
is, and `sheet`: with which the map is put on a sheet with a margin and a grid; `name`, `credits` and `date`
|
|
are written on it, `contours` (`{"interval": 40, "unit": "feet"}`, or "meters") when the map has contour
|
|
lines, and `legend`: the lines of the map as they are drawn (see `modules.map.sheet.Sheet`)."""
|
|
try:
|
|
meta = request.json
|
|
width, height, dpi = int(meta['width']), int(meta['height']), float(meta['dpi'])
|
|
names = [_export_text(i) for i in meta['layers']]
|
|
title = _export_text(meta.get('title')) or None
|
|
bounds = meta.get('bounds')
|
|
sheet = meta.get('sheet')
|
|
if sheet is not None:
|
|
sheet = export.Sheet(
|
|
name=_export_text(sheet.get('name')) or None,
|
|
credits=[_export_text(i) for i in (sheet.get('credits') or [])[:SHEET_CREDITS]],
|
|
date=_export_text(sheet.get('date')) or None,
|
|
**_sheet_contours(sheet.get('contours')),
|
|
legend=legend_as_sent(sheet.get('legend')),
|
|
)
|
|
except Exception: # noqa Whatever is made of a body which is not the description of a map.
|
|
return response.json({'error': 'The description of the map is not valid'}, HTTPStatus.BAD_REQUEST)
|
|
|
|
try:
|
|
# Old exports are removed from the disk here, which is not for the event loop.
|
|
export_id = await asyncio.to_thread(export_job.create_export, names, width, height, dpi, title, bounds, sheet)
|
|
except EXPORT_ERRORS as e:
|
|
return _export_error(e)
|
|
return json_response({'export_id': export_id}, HTTPStatus.CREATED)
|
|
|
|
|
|
@map_bp.post('/export/<export_id:str>/layer/<index:int>')
|
|
@openapi.description('Send the image (PNG or JPEG) of one layer of a map which is being exported')
|
|
async def post_export_layer(request: Request, export_id: str, index: int):
|
|
try:
|
|
await asyncio.to_thread(export_job.save_layer, export_id, index, request.body)
|
|
except EXPORT_ERRORS as e:
|
|
return _export_error(e)
|
|
return response.empty()
|
|
|
|
|
|
@map_bp.post('/export/<export_id:str>/start')
|
|
@openapi.description('Queue the Job which makes the PDF of a map, all of whose layers have been sent')
|
|
async def post_export_start(_: Request, export_id: str):
|
|
try:
|
|
job_id = await asyncio.to_thread(export_job.start_export, export_id)
|
|
except EXPORT_ERRORS as e:
|
|
return _export_error(e)
|
|
return json_response({'job_id': job_id}, HTTPStatus.ACCEPTED)
|
|
|
|
|
|
@map_bp.delete('/export/<export_id:str>')
|
|
@openapi.description('Stop the export of a map: cancel its Job, if it has one, and remove what was sent')
|
|
async def delete_export(_: Request, export_id: str):
|
|
try:
|
|
await asyncio.to_thread(export_job.remove_export, export_id)
|
|
except EXPORT_ERRORS as e:
|
|
return _export_error(e)
|
|
return response.empty()
|
|
|
|
|
|
@map_bp.get('/export/<export_id:str>/pdf')
|
|
@openapi.description('The PDF of an exported map, once the Job which makes it is complete')
|
|
async def get_export_pdf(_: Request, export_id: str):
|
|
try:
|
|
pdf = await asyncio.to_thread(export_job.get_export_pdf, export_id)
|
|
except EXPORT_ERRORS as e:
|
|
return _export_error(e)
|
|
return await response.file(pdf, mime_type='application/pdf', filename='map.pdf')
|
|
|
|
|
|
@map_bp.get('/fallout/climatology')
|
|
@openapi.description('Which months of the fallout climatology (30 past days of winds each) are kept')
|
|
def get_fallout_climatology(_: Request):
|
|
return json_response(climatology.status(), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/fallout/climatology/<month:int>')
|
|
@openapi.description('One month of the fallout climatology, as kept (gzip)')
|
|
async def get_fallout_climatology_month(_: Request, month: int):
|
|
path = climatology.month_path(month)
|
|
if not path:
|
|
return response.json({'error': f'Month {month} of the climatology is not kept'}, HTTPStatus.NOT_FOUND)
|
|
return await response.file(path, mime_type='application/octet-stream')
|
|
|
|
|
|
@map_bp.get('/fallout/winds/latest')
|
|
@openapi.description('The field of forecast winds aloft fetched most recently')
|
|
def get_latest_fallout_winds(_: Request):
|
|
return json_response(dict(winds=winds.latest_field()), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.get('/weather')
|
|
@openapi.description('The weather subscription: whether it is on, its download, and the forecast kept')
|
|
def get_weather(request: Request):
|
|
return json_response(winds.weather_status(request.ctx.session), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.put('/weather')
|
|
@openapi.description('Subscribe to the weather (a forecast around the nuclear targets, every day), or not')
|
|
@validate(schema.MapWeatherRequest)
|
|
@wrol_mode_check
|
|
async def put_weather(request: Request, body: schema.MapWeatherRequest):
|
|
with request.ctx.db.write() as session:
|
|
winds.set_weather_subscription(session, bool(body.enabled))
|
|
return json_response(winds.weather_status(request.ctx.session), HTTPStatus.OK)
|
|
|
|
|
|
@map_bp.post('/weather/download')
|
|
@openapi.description('Download the weather now, rather than when it is next due')
|
|
@wrol_mode_check
|
|
async def post_weather_download(request: Request):
|
|
with request.ctx.db.write() as session:
|
|
if not winds.download_weather_now(session):
|
|
return response.json({'error': 'The weather is not subscribed to'}, HTTPStatus.BAD_REQUEST)
|
|
return json_response(winds.weather_status(request.ctx.session), HTTPStatus.OK)
|