Add the place loader and membership
This commit is contained in:
1 parent
c29f9370fe
commit
4afa05cdff
2 files changed
+369
No files matched your search
@@ -0,0 +1,186 @@
|
||||
"""National parks, mountain ranges and wilderness areas: the places.toml registry
|
||||
and which trails are in each place (the [[place]] tables of the records).
|
||||
|
||||
Membership is closed over the registry's `within` here, at build time: a trail in a
|
||||
nested range is in every parent range too, though its record never names a parent.
|
||||
A place has a page only with PAGE_MIN or more trails, counting measured (`track`)
|
||||
and hand-entered (`stated`) placements alike. Below that it has no page and no link.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from . import datafiles, facets, words
|
||||
|
||||
PAGE_MIN = 3
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Kind:
|
||||
key: str # the registry kind: "park", "range", "wilderness"
|
||||
segment: str # the first part of the page's address: /parks/<slug>/
|
||||
hub_title: str # the Places hub section's heading
|
||||
noun: str # one place of this kind, for a page's kicker
|
||||
|
||||
|
||||
KINDS = {
|
||||
"park": Kind("park", "parks", "Parks", "Park"),
|
||||
"range": Kind("range", "ranges", "Mountain ranges", "Mountain range"),
|
||||
"wilderness": Kind("wilderness", "wilderness", "Wilderness areas", "Wilderness area"),
|
||||
}
|
||||
KIND_ORDER = {key: i for i, key in enumerate(KINDS)}
|
||||
|
||||
|
||||
def load(repo_root):
|
||||
"""The place registry of places.toml, keyed (kind, slug). Slugs repeat across kinds."""
|
||||
out = {}
|
||||
for e in datafiles.places(repo_root):
|
||||
if isinstance(e, dict) and e.get("kind") and e.get("slug"):
|
||||
out[(e["kind"], e["slug"])] = e
|
||||
return out
|
||||
|
||||
|
||||
def path(kind, slug):
|
||||
"""The page of a place: /parks/glacier/, /ranges/wind-river-range/, /wilderness/<slug>/."""
|
||||
return f"/{KINDS[kind].segment}/{slug}/"
|
||||
|
||||
|
||||
def _parents(registry):
|
||||
"""(kind, slug) -> its parent (kind, slug)s. A `within` parent is always a range."""
|
||||
return {key: [("range", s) for s in (e.get("within") or []) if ("range", s) in registry]
|
||||
for key, e in registry.items()}
|
||||
|
||||
|
||||
def _closure(key, parents):
|
||||
"""The place itself and every ancestor, each once (a `within` cycle cannot loop)."""
|
||||
seen, stack = [], [key]
|
||||
while stack:
|
||||
k = stack.pop(0)
|
||||
if k in seen:
|
||||
continue
|
||||
seen.append(k)
|
||||
stack += parents.get(k, [])
|
||||
return seen
|
||||
|
||||
|
||||
def membership(records, registry):
|
||||
"""(kind, slug) -> the records in the place, deduplicated and A to Z, closed over
|
||||
`within`. Every registry place is a key, with no records when none is in it. A place
|
||||
a record names that the registry does not hold is ignored (the validator refuses it)."""
|
||||
parents = _parents(registry)
|
||||
out = {key: [] for key in registry}
|
||||
seen = {key: set() for key in registry}
|
||||
for rec in records:
|
||||
for p in rec.get("place") or []:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
key = (p.get("kind"), p.get("slug"))
|
||||
if key not in registry:
|
||||
continue
|
||||
for k in _closure(key, parents):
|
||||
if rec["id"] not in seen[k]:
|
||||
seen[k].add(rec["id"])
|
||||
out[k].append(rec)
|
||||
for recs in out.values():
|
||||
recs.sort(key=facets.sort_name)
|
||||
return out
|
||||
|
||||
|
||||
def _state_key(code):
|
||||
""""WY" -> "US-WY"; a code already carrying its country ("us-wy") is put in the same form."""
|
||||
code = str(code or "").strip()
|
||||
if "-" in code:
|
||||
country, _, rest = code.partition("-")
|
||||
return f"{country.upper()}-{rest.upper()}"
|
||||
country = words.region_country(code)
|
||||
return f"{country}-{code}" if country else code
|
||||
|
||||
|
||||
def state_names(info):
|
||||
"""The full names of the states and provinces a place is in ("Wyoming"), from its `where`."""
|
||||
return [words.region_name(_state_key(c).split("-", 1)[-1]) for c in info.get("where") or []]
|
||||
|
||||
|
||||
def title_name(info):
|
||||
"""The place as a page title names it: a park by its name alone; a range or a
|
||||
wilderness area in one state or province with that state spelled out
|
||||
("Wind River Range, Wyoming"), and with no state when it spans several."""
|
||||
name = info["name"]
|
||||
if info.get("kind") == "park":
|
||||
return name
|
||||
names = state_names(info)
|
||||
return f"{name}, {names[0]}" if len(names) == 1 else name
|
||||
|
||||
|
||||
_NAME_ENDS = (" national park", " provincial park", " wilderness area", " park", " wilderness")
|
||||
|
||||
|
||||
def _core(name):
|
||||
text = " ".join(str(name).lower().split())
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for end in _NAME_ENDS:
|
||||
if text.endswith(end) and len(text) > len(end):
|
||||
text = text[:-len(end)].strip()
|
||||
changed = True
|
||||
return text
|
||||
|
||||
|
||||
def _doubled(park_name, wild_name):
|
||||
"""True when a park and a wilderness area are the same ground under two names: one
|
||||
name holds the other, or the names differ only in the kind words at the end."""
|
||||
a, b = " ".join(str(park_name).lower().split()), " ".join(str(wild_name).lower().split())
|
||||
if a in b or b in a:
|
||||
return True
|
||||
return bool(_core(a)) and _core(a) == _core(b)
|
||||
|
||||
|
||||
def collect(records, registry):
|
||||
"""(kind, slug) -> info for every place with a page: PAGE_MIN or more trails.
|
||||
|
||||
An info holds kind, slug, key ("<kind>/<slug>"), name, where, box, records, path
|
||||
and title_name. A wilderness area that holds exactly the trails of a national park
|
||||
of much the same name gets no page: one page for the one set, under the park. The
|
||||
registry normally already leaves such a wilderness out; the builder stays safe."""
|
||||
mem = membership(records, registry)
|
||||
out = {}
|
||||
for (kind, slug), recs in mem.items():
|
||||
if len(recs) < PAGE_MIN:
|
||||
continue
|
||||
e = registry[(kind, slug)]
|
||||
info = {"kind": kind, "slug": slug, "key": f"{kind}/{slug}", "name": e.get("name", slug),
|
||||
"where": list(e.get("where") or []), "box": e.get("box"), "records": recs,
|
||||
"path": path(kind, slug)}
|
||||
info["title_name"] = title_name(info)
|
||||
out[(kind, slug)] = info
|
||||
parks = [i for i in out.values() if i["kind"] == "park"]
|
||||
for key, info in list(out.items()):
|
||||
if info["kind"] != "wilderness":
|
||||
continue
|
||||
ids = {r["id"] for r in info["records"]}
|
||||
if any({r["id"] for r in p["records"]} == ids and _doubled(p["name"], info["name"])
|
||||
for p in parks):
|
||||
del out[key]
|
||||
return out
|
||||
|
||||
|
||||
def _infos(infos):
|
||||
return list(infos.values()) if isinstance(infos, dict) else list(infos or ())
|
||||
|
||||
|
||||
def _by_kind_then_name(infos):
|
||||
return sorted(infos, key=lambda i: (KIND_ORDER.get(i["kind"], 99), i["name"].lower()))
|
||||
|
||||
|
||||
def in_state(infos, state_key):
|
||||
"""The places with a page that lie in one state or province (state_key as in
|
||||
olt/facets.py, "US-WY"), by kind then name."""
|
||||
want = _state_key(state_key)
|
||||
return _by_kind_then_name([i for i in _infos(infos)
|
||||
if want in {_state_key(c) for c in i.get("where") or []}])
|
||||
|
||||
|
||||
def of_record(rec, infos):
|
||||
"""The places of one trail that have a page, by kind then name. A parent range is
|
||||
among them: the infos' records are already closed over `within`."""
|
||||
return _by_kind_then_name([i for i in _infos(infos)
|
||||
if any(r["id"] == rec["id"] for r in i["records"])])
|
||||
@@ -0,0 +1,183 @@
|
||||
"""The place loader: registry, membership closed over `within`, and which places
|
||||
get a page (olt/places.py). Fixtures only; no built site."""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, WEB)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from olt import places # noqa: E402
|
||||
from test_hike import fake # noqa: E402
|
||||
|
||||
|
||||
def entry(kind, slug, name, where=("WY",), within=()):
|
||||
return {"kind": kind, "slug": slug, "name": name, "where": list(where),
|
||||
"within": list(within), "source": "gmba-v2", "source_id": "1",
|
||||
"source_version": "2026-11-20", "box": [-110.0, 42.5, -108.5, 43.5]}
|
||||
|
||||
|
||||
def registry(*entries):
|
||||
return {(e["kind"], e["slug"]): e for e in entries}
|
||||
|
||||
|
||||
def rec(i, *pls, name=None):
|
||||
r = fake(i)
|
||||
if name:
|
||||
r["name"] = name
|
||||
r["place"] = [{"kind": k, "slug": s, "basis": b,
|
||||
**({"km": 10.0} if b == "track" else {"source": "https://example.org/"})}
|
||||
for k, s, b in pls]
|
||||
return r
|
||||
|
||||
|
||||
WIND = entry("range", "wind-river-range", "Wind River Range")
|
||||
YOSE = entry("park", "yosemite", "Yosemite National Park", where=("CA",))
|
||||
|
||||
|
||||
class CollectTest(unittest.TestCase):
|
||||
def test_a_range_gets_a_page_at_three_trails_and_not_at_two(self):
|
||||
reg = registry(WIND)
|
||||
two = [rec(1, ("range", "wind-river-range", "track")),
|
||||
rec(2, ("range", "wind-river-range", "track"))]
|
||||
self.assertEqual(places.collect(two, reg), {})
|
||||
three = two + [rec(3, ("range", "wind-river-range", "track"))]
|
||||
got = places.collect(three, reg)
|
||||
self.assertEqual(list(got), [("range", "wind-river-range")])
|
||||
info = got[("range", "wind-river-range")]
|
||||
self.assertEqual(info["path"], "/ranges/wind-river-range/")
|
||||
self.assertEqual(info["key"], "range/wind-river-range")
|
||||
self.assertEqual([r["id"] for r in info["records"]], ["t1", "t2", "t3"])
|
||||
|
||||
def test_stated_and_track_trails_both_count(self):
|
||||
reg = registry(WIND)
|
||||
recs = [rec(1, ("range", "wind-river-range", "track")),
|
||||
rec(2, ("range", "wind-river-range", "stated")),
|
||||
rec(3, ("range", "wind-river-range", "track"))]
|
||||
self.assertIn(("range", "wind-river-range"), places.collect(recs, reg))
|
||||
|
||||
def test_a_trail_in_a_nested_range_is_on_every_parent(self):
|
||||
teton = entry("range", "teton-range", "Teton Range", within=("rocky-mountains",))
|
||||
rocky = entry("range", "rocky-mountains", "Rocky Mountains",
|
||||
where=("WY", "CO", "MT"), within=("cordillera",))
|
||||
cord = entry("range", "cordillera", "Cordillera", where=("WY", "CO"))
|
||||
reg = registry(teton, rocky, cord)
|
||||
recs = [rec(i, ("range", "teton-range", "track")) for i in (1, 2, 3)]
|
||||
mem = places.membership(recs, reg)
|
||||
for slug in ("teton-range", "rocky-mountains", "cordillera"):
|
||||
self.assertEqual([r["id"] for r in mem[("range", slug)]], ["t1", "t2", "t3"], slug)
|
||||
self.assertIn(("range", "rocky-mountains"), places.collect(recs, reg))
|
||||
|
||||
def test_slugs_repeat_across_kinds(self):
|
||||
park = entry("park", "glacier", "Glacier National Park", where=("MT",))
|
||||
wild = entry("wilderness", "glacier", "Glacier Peak Wilderness", where=("WA",))
|
||||
reg = registry(park, wild)
|
||||
recs = [rec(i, ("park", "glacier", "track")) for i in (1, 2, 3)]
|
||||
recs += [rec(i, ("wilderness", "glacier", "track")) for i in (4, 5, 6)]
|
||||
got = places.collect(recs, reg)
|
||||
self.assertEqual(got[("park", "glacier")]["path"], "/parks/glacier/")
|
||||
self.assertEqual(got[("wilderness", "glacier")]["path"], "/wilderness/glacier/")
|
||||
self.assertEqual([r["id"] for r in got[("park", "glacier")]["records"]], ["t1", "t2", "t3"])
|
||||
self.assertEqual([r["id"] for r in got[("wilderness", "glacier")]["records"]], ["t4", "t5", "t6"])
|
||||
|
||||
def test_a_parent_is_counted_once_when_a_trail_is_in_two_children(self):
|
||||
a = entry("range", "a-range", "A Range", within=("parent-range",))
|
||||
b = entry("range", "b-range", "B Range", within=("parent-range",))
|
||||
p = entry("range", "parent-range", "Parent Range")
|
||||
reg = registry(a, b, p)
|
||||
recs = [rec(1, ("range", "a-range", "track"), ("range", "b-range", "track"))]
|
||||
mem = places.membership(recs, reg)
|
||||
self.assertEqual([r["id"] for r in mem[("range", "parent-range")]], ["t1"])
|
||||
|
||||
def test_a_doubled_wilderness_gets_no_page_when_the_park_holds_the_same_trails(self):
|
||||
park = entry("park", "example", "Example National Park", where=("CA",))
|
||||
wild = entry("wilderness", "example", "Example National Park Wilderness", where=("CA",))
|
||||
reg = registry(park, wild)
|
||||
recs = [rec(i, ("park", "example", "track"), ("wilderness", "example", "track"))
|
||||
for i in (1, 2, 3)]
|
||||
got = places.collect(recs, reg)
|
||||
self.assertIn(("park", "example"), got)
|
||||
self.assertNotIn(("wilderness", "example"), got)
|
||||
# different sets: both keep their pages
|
||||
recs.append(rec(4, ("wilderness", "example", "track")))
|
||||
self.assertIn(("wilderness", "example"), places.collect(recs, reg))
|
||||
|
||||
def test_records_are_a_to_z(self):
|
||||
reg = registry(WIND)
|
||||
recs = [rec(1, ("range", "wind-river-range", "track"), name="Zebra Trail"),
|
||||
rec(2, ("range", "wind-river-range", "track"), name="The Apple Trail"),
|
||||
rec(3, ("range", "wind-river-range", "track"), name="Middle Trail")]
|
||||
got = places.collect(recs, reg)[("range", "wind-river-range")]
|
||||
self.assertEqual([r["name"] for r in got["records"]],
|
||||
["The Apple Trail", "Middle Trail", "Zebra Trail"])
|
||||
|
||||
def test_title_name_adds_the_state_for_a_range_with_one_state_only(self):
|
||||
reg = registry(WIND, YOSE)
|
||||
recs = [rec(i, ("range", "wind-river-range", "track"), ("park", "yosemite", "track"))
|
||||
for i in (1, 2, 3)]
|
||||
got = places.collect(recs, reg)
|
||||
self.assertEqual(got[("range", "wind-river-range")]["title_name"],
|
||||
"Wind River Range, Wyoming")
|
||||
self.assertEqual(places.title_name(got[("range", "wind-river-range")]),
|
||||
"Wind River Range, Wyoming")
|
||||
self.assertEqual(got[("park", "yosemite")]["title_name"], "Yosemite National Park")
|
||||
multi = dict(got[("range", "wind-river-range")], where=["WY", "CO", "MT", "UT"])
|
||||
self.assertEqual(places.title_name(multi), "Wind River Range")
|
||||
|
||||
def test_of_record_leaves_out_a_place_below_the_minimum(self):
|
||||
small = entry("park", "small", "Small Park", where=("WY",))
|
||||
reg = registry(WIND, small)
|
||||
recs = [rec(1, ("range", "wind-river-range", "track"), ("park", "small", "track"))]
|
||||
recs += [rec(i, ("range", "wind-river-range", "track")) for i in (2, 3)]
|
||||
infos = places.collect(recs, reg)
|
||||
mine = places.of_record(recs[0], infos)
|
||||
self.assertEqual([(i["kind"], i["slug"]) for i in mine], [("range", "wind-river-range")])
|
||||
|
||||
def test_of_record_includes_a_parent_range(self):
|
||||
teton = entry("range", "teton-range", "Teton Range", within=("rocky-mountains",))
|
||||
rocky = entry("range", "rocky-mountains", "Rocky Mountains", where=("WY", "CO"))
|
||||
reg = registry(teton, rocky)
|
||||
recs = [rec(i, ("range", "teton-range", "track")) for i in (1, 2, 3)]
|
||||
infos = places.collect(recs, reg)
|
||||
names = [i["name"] for i in places.of_record(recs[0], infos)]
|
||||
self.assertEqual(names, ["Rocky Mountains", "Teton Range"])
|
||||
|
||||
def test_in_state_matches_the_registry_where(self):
|
||||
reg = registry(WIND, YOSE)
|
||||
recs = [rec(i, ("range", "wind-river-range", "track"), ("park", "yosemite", "track"))
|
||||
for i in (1, 2, 3)]
|
||||
infos = places.collect(recs, reg)
|
||||
wy = places.in_state(infos, "US-WY")
|
||||
self.assertEqual([i["name"] for i in wy], ["Wind River Range"])
|
||||
self.assertEqual(places.in_state(infos, "US-UT"), [])
|
||||
|
||||
def test_path_and_kinds(self):
|
||||
self.assertEqual(places.path("park", "glacier"), "/parks/glacier/")
|
||||
self.assertEqual(places.path("range", "wind-river-range"), "/ranges/wind-river-range/")
|
||||
self.assertEqual(places.path("wilderness", "bob-marshall"), "/wilderness/bob-marshall/")
|
||||
self.assertEqual(places.KINDS["park"].segment, "parks")
|
||||
self.assertEqual(places.KINDS["range"].segment, "ranges")
|
||||
self.assertEqual(places.KINDS["wilderness"].segment, "wilderness")
|
||||
self.assertEqual(places.PAGE_MIN, 3)
|
||||
|
||||
def test_load_reads_places_toml_keyed_by_kind_and_slug(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
with open(os.path.join(d, "places.toml"), "w", encoding="utf-8") as f:
|
||||
f.write('[[place]]\nslug = "wind-river-range"\nkind = "range"\n'
|
||||
'name = "Wind River Range"\nwhere = ["WY"]\nsource = "gmba-v2"\n'
|
||||
'source_id = "1"\nsource_version = "2026-11-20"\n'
|
||||
'box = [-110.0, 42.5, -108.5, 43.5]\n')
|
||||
reg = places.load(d)
|
||||
self.assertEqual(reg[("range", "wind-river-range")]["name"], "Wind River Range")
|
||||
|
||||
def test_an_unknown_place_on_a_record_is_ignored(self):
|
||||
reg = registry(WIND)
|
||||
recs = [rec(1, ("range", "nowhere", "track"))]
|
||||
self.assertEqual(places.collect(recs, reg), {})
|
||||
self.assertEqual(places.membership(recs, reg)[("range", "wind-river-range")], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user