Merge branch 'main' into fast-tests-2

This commit is contained in:
swaits committed 2026-11-20 16:28:12 -07:00
commit 69871fc764
128 files changed
+7921 -300

No files matched your search

+1 -1
View File
@@ -312,7 +312,7 @@ def author_page(g, records, site, all_pages):
+ " · ".join(f'<a href="{esc(path(x))}">{esc(x["name"])}</a> ({len(x["routes"])})' for x in nav_items) + "</nav>") if nav_items else ""
more = str(summary.facts(routes, records, by_authors=False)) if n >= 3 else ""
briefs = "".join(f'<h3><a href="{esc(common.trail_path(r))}">{esc(common.plain_name(r))}</a></h3>\n{trail.brief(r)}\n' for r in routes)
listing = home.results(groups=[(None, routes, regions.route_guides)], routes_list=True, top=2,
listing = home.listing(groups=[(None, routes, regions.route_guides)], routes_list=True, top=2,
by=lambda r: with_html(g, r, by_name))
route_title = "About the route" if n == 1 else "About each route"
bio = about_html(g)
+26 -10
View File
@@ -55,6 +55,9 @@ class List:
note: Optional[Callable] = None
# A larger least size than MIN_SIZE, where the list is thin by nature (a month's list).
min_size: int = 0
# False for a list that is one of a fixed set, so none may go missing: a month's list, however
# many of the trails are walked in it, is not "nearly everything" but one of twelve.
capped: bool = True
def search_title(self, n):
return (self.page_title or f"{self.title}: {{n}} Trails").format(n=n)
@@ -79,7 +82,7 @@ GROUPS = (
("walking", "By kind of walking", "Loops, high routes, walking with no trail, and trails not yet finished."),
("terrain", "By terrain", "The main kinds of country a trail crosses."),
("holder", "By who looks after it", "Trails whose designation names the holder."),
("month", "By month", "Trails whose season on file includes the month. Only some trails have a season."),
("month", "By month", "Trails normally hiked in the month. Estimated seasons are marked."),
("where", "By country and GPX", "Where a trail is, and whether its page has a track to download."),
)
@@ -116,17 +119,29 @@ def time_note(recs, records):
def _month_list(m):
name = facets.MONTHS[m - 1]
return List(f"hike-in-{name.lower()}", f"Hiking in {name}",
f"Trails whose season on file includes {name}.",
f"Trails normally hiked in {name}. Estimated seasons are marked.",
lambda r, m=m: m in facets.months(r),
page_title=f"Long Trails to Hike in {name}: {{n}} Trails", group="month", note=month_note(name),
min_size=MONTH_MIN)
min_size=MONTH_MIN, capped=False)
def month_note(name):
def note(recs, records):
have = sum(1 for r in records if facets.months(r))
return (f"Only {have} of the {len(records)} trails have a season on file, so this page covers those "
f"{have}. It is not every trail that can be walked in {name}.")
unstated = [r for r in recs if facets.season_estimated(r)]
est = len(unstated)
stated = len(recs) - est
if not est:
return f"A source states the season for all {stated}."
kinds = {facets.season_kind(r) for r in unstated}
one = ("estimated from the climate and similar trails" if kinds == {"estimated"}
else "set by judgement from pages that differ" if kinds == {"judged"} else "")
if not stated:
return (f"No source states the season for these, so each is {one}." if one
else f"No source states the season for these: {facets.season_unstated_clause(unstated)}.")
if one:
return f"A source states the season for {stated} of these. For the other {est} it is {one}, and marked."
return (f"A source states the season for {stated} of these. For the other {est}, "
f"{facets.season_unstated_clause(unstated)}, and marked.")
return note
@@ -266,10 +281,11 @@ def members(lst, records):
return facets.sort_records([r for r in records if lst.test(r)], lst.sort)
def is_shown(n, total, least=0):
def is_shown(n, total, least=0, capped=True):
"""The threshold rule: a list is shown when it holds at least MIN_SIZE
trails (or `least`, where the list asks for more) and no more than MAX_SHARE of all of them."""
return n >= max(MIN_SIZE, least) and n <= MAX_SHARE * total
trails (or `least`, where the list asks for more) and no more than MAX_SHARE of all of them,
unless it is not capped (the twelve month lists)."""
return n >= max(MIN_SIZE, least) and (not capped or n <= MAX_SHARE * total)
_SHOWN_MEMO = None # while a site is being rendered: {id(records): (records, shown)}
@@ -296,7 +312,7 @@ def shown(records):
out = []
for lst in LISTS:
recs = members(lst, records)
if is_shown(len(recs), len(records), lst.min_size):
if is_shown(len(recs), len(records), lst.min_size, lst.capped):
out.append((lst, recs))
if _SHOWN_MEMO is not None:
_SHOWN_MEMO[id(records)] = (records, out)
+13
View File
@@ -5,11 +5,13 @@
[[list]] which lists the home page shows, and in what order (olt/home.py)
authors.toml [[author]] route authors, and the words about the people among them (olt/authors.py)
places.toml [[place]] the parks, mountain ranges and wilderness areas records name
tools/season_blind_test.json how the judged seasons did against the seasons pages state (olt/reference.py)
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
is looked for in the repository being built and then in this one, so a test repository without
one still builds.
"""
import json
import os
import tomllib
@@ -46,3 +48,14 @@ def places(repo_root):
def lists(repo_root):
"""The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row."""
return load(repo_root, "collections.toml", "list")
def blind_test(repo_root):
"""The blind test of the judged seasons (tools/season_blind_test.json, written by
tools/season_judge.py score), or None when there is none."""
for base in (repo_root, REAL_ROOT):
path = os.path.join(base or REAL_ROOT, "tools", "season_blind_test.json")
if os.path.isfile(path):
with open(path, encoding="utf-8") as f:
return json.load(f)
return None
+106 -6
View File
@@ -172,8 +172,15 @@ def months(rec):
return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12})
def season_text(rec):
"""The phrase on the trail page: [hike].season, else built from the months."""
def season_estimated(rec):
"""True when no page states the season: it was estimated (season_basis "estimate"), or set by
judgement from pages that differ (it carries a season_method). Such a season reads "About"."""
h = hike.table(rec)
return bool(h.get("season")) and (h.get("season_basis") == "estimate" or bool((h.get("season_method") or "").strip()))
def season_phrase(rec):
"""The phrase on the trail page as the record gives it: [hike].season, else built from the months."""
phrase = (hike.table(rec).get("season") or "").strip()
if phrase:
return phrase[:1].upper() + phrase[1:]
@@ -185,6 +192,97 @@ def season_text(rec):
return words.join_names(MONTHS[m - 1] for m in ms)
def season_text(rec):
"""The season as a page shows it: the phrase, or "About ..." where it is estimated, so an
estimate never reads as a stated fact ("About June to September", "About all year")."""
phrase = season_phrase(rec)
if not phrase or not season_estimated(rec):
return phrase
if phrase.lower().startswith("about"):
return phrase
if phrase.lower() == "all year":
phrase = phrase.lower()
return "About " + phrase
def season_kind(rec):
"""How the season is known: "stated" (a page states it), "judged" (set by judgement from pages
that differ), "estimated" (no page states one), or "" when the trail has no season."""
if not hike.table(rec).get("season"):
return ""
if not season_estimated(rec):
return "stated"
return "judged" if season_basis(rec) == "sources" else "estimated"
SEASON_CONFIDENCE = re.compile(r"\s*Confidence: (high|medium|low)\.\s*$")
JUDGED_LEAD = "Judged from the climate at the trail's elevation and from similar trails."
def season_confidence(rec):
""""high", "medium" or "low" from the end of the season's method; "" when it names none."""
found = SEASON_CONFIDENCE.search(hike.table(rec).get("season_method") or "")
return found.group(1) if found else ""
def season_reason(rec):
"""What the season's method says sets the season, without its standard first sentence and its
closing confidence."""
text = SEASON_CONFIDENCE.sub("", (hike.table(rec).get("season_method") or "").strip()).strip()
if text.startswith(JUDGED_LEAD):
text = text[len(JUDGED_LEAD):].strip()
return text
def season_pages_differ(rec):
"""True for a season set by judgement from pages that state different seasons."""
return season_estimated(rec) and season_basis(rec) == "sources"
SEASON_USUAL = "This is the usual window, not a closure."
def _plural(n, one, many):
return f"{n} {one if n == 1 else many}"
def season_unstated_clause(recs):
"""What is true of the seasons among recs that no page states, kind by kind and counted exactly:
"2 are estimated from the climate and similar trails and 1 is set by judgement from pages that
differ"; "" when there are none."""
kinds = [season_kind(r) for r in recs]
est, judged = kinds.count("estimated"), kinds.count("judged")
parts = []
if est:
parts.append(f"{est} {'is' if est == 1 else 'are'} estimated from the climate and similar trails")
if judged:
parts.append(f"{judged} {'is' if judged == 1 else 'are'} set by judgement from pages that differ")
return " and ".join(parts)
def season_note(rec):
"""Says an estimated season is not a page's statement, how it was worked out, what sets it
there and how far to trust it; "" when a page states the season."""
if not season_estimated(rec):
return ""
reason = season_reason(rec)
if season_pages_differ(rec):
lead = "No one page states this season."
elif "estimated from the climate" in reason:
lead = "No page states a season." # the method says how it was estimated; not said twice
else:
lead = ("No page states a season. This is estimated from the climate at the trail's "
"elevation and from similar trails.")
parts = [lead]
if reason:
parts.append(reason)
conf = season_confidence(rec)
if conf:
parts.append(f"Confidence: {conf}.")
parts.append(SEASON_USUAL)
return " ".join(parts)
SEASON_BASIS_TEXT = {
"primary": "The season comes from the page of the body that manages the trail or the trail's own association or, for a route, its author.",
"sources": "Two or more pages from different publishers agree on the season.",
@@ -203,10 +301,12 @@ def season_basis(rec):
def season_basis_line(rec):
"""One sentence for "About this data"; "" when the season has no recorded basis."""
basis = season_basis(rec)
if basis == "estimate":
method = (hike.table(rec).get("season_method") or "").strip()
return (method + " No page states a season.").strip()
return SEASON_BASIS_TEXT.get(basis, "")
if not season_estimated(rec):
return SEASON_BASIS_TEXT.get(basis, "")
method = (hike.table(rec).get("season_method") or "").strip()
if season_pages_differ(rec):
return (method + " It is a judgement, not any one page's statement.").strip()
return (method + " No page states a season.").strip()
# Terrain, Walking, Shape ----------------------------------------------------
+46 -27
View File
@@ -193,6 +193,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
if search:
data["search"] = searchtext.attribute(rec)
attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items())
estimated = facets.season_estimated(rec)
if estimated:
attrs += ' data-estimate="yes"'
if common.line_differs(rec):
attrs += ' data-partial="yes"'
h = f"h{level}"
@@ -203,6 +206,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
desc = entry_desc(rec)
desc_html = f'\n <p class="entry__desc">{esc(desc)}</p>' if desc else ""
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
season_html = (f'\n <div class="entry__season"><dt>{facets.SEASON}</dt><dd>{esc(facets.season_text(rec))}'
+ ('<small class="entry__est">estimate</small>' if estimated else "") + "</dd></div>"
if facets.months(rec) else "")
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(climb_m, "stack")}'
f'<small class="entry__est">computed</small></dd></div>') if climb_m is not None else ""
if hidden:
@@ -227,23 +233,19 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
<dl class="entry__facts">{lead_html}
<div class="entry__length"><dt>Length</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}<span class="loglen" style="--km: {rec["length_km"]}" aria-hidden="true"></span></dd></div>
<div class="entry__time"><dt>Time</dt><dd>{time_html}</dd></div>
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{climb_html}{more_html}
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{season_html}{climb_html}{more_html}
</dl>{extra}
</li>"""
# The filters ------------------------------------------------------------------
# One bar and one set of panels, on the home page and on every other page that shows a set of at
# least FILTER_MIN trails (listing()), and on every park, range and wilderness page whatever its
# size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
# One bar and one set of panels, on the home page and on every other page that shows a set of
# trails (listing()), whatever its size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
# cannot narrow them is left out, and an option none of them has is not written. The numbers written
# here are for the whole set; app.js counts again from the rows on the page every time anything
# changes, and hides an option that would show nothing (its counting is facetCounts(), which
# web/tests/test_filter_counts.py runs under node against counts made here from the records).
FILTER_MIN = 10
def _length_options(steps, selected_any_last, unit="mi"):
opts = [f'<option value="{step_value(n, unit)}">{step_label(n, unit)}</option>' for n in steps]
if selected_any_last:
@@ -334,7 +336,7 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
<label class="field__label" for="where">{facets.WHERE}</label>
<select class="select" id="where" name="where">{opts}</select>
</div>""")
kms = [r["length_km"] for r in records]
kms = [r["length_km"] for r in records] or [0]
if any(min(kms) < n * words.KM_PER_MI <= max(kms) for n in steps):
first.append(f"""<fieldset class="field" data-facet="length">
<legend>{facets.LENGTH}</legend>
@@ -355,10 +357,14 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
</fieldset>""")
if facets.offered(records, "season") and _narrows(c, "month", range(1, 13)):
month_opts = "".join(_opt(str(i), m, c[f"month:{i}"]) for i, m in enumerate(facets.MONTHS, 1) if c[f"month:{i}"])
# A way to leave estimated seasons out, offered only where some of these trails have one.
stated_box = ('\n <label class="field__check"><input type="checkbox" name="stated" value="1" disabled> '
'Leave out estimated seasons</label>'
if any(facets.season_estimated(r) for r in records) else "")
first.append(f"""<div class="field" data-facet="month">
<label class="field__label" for="month">{facets.SEASON}</label>
<select class="select" id="month" name="month"><option value="">Any month</option>{month_opts}</select>
<p class="field__hint">Trails usually walked in that month.</p>
<p class="field__hint">Trails usually walked in that month. Estimated seasons are marked.</p>{stated_box}
{_missing(records, "season")}
</div>""")
if _narrows(c, "kind", facets.KINDS):
@@ -433,15 +439,13 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
</form>"""
def listing(recs=None, *, where="all", groups=None, always=False, **kw):
"""The rows of a page that shows a set of trails, with the filter bar over them when the set
has at least FILTER_MIN trails (else results() alone); with always, whatever its size (the
bar then holds only the filters that have something to offer). where: the Where filter's
scope (finder_form). The other arguments are results()'s."""
def listing(recs=None, *, where="all", groups=None, **kw):
"""The rows of a page that shows a set of trails, with the filter bar over them whatever the size
of the set (the bar holds only the filters that have something to offer, and the search box
alone where nothing can narrow the set). where: the Where filter's scope (finder_form). The
other arguments are results()'s."""
trails = [r for g in groups for r in g[1]] if groups is not None else list(recs)
if len(trails) < FILTER_MIN and not always:
return results(recs, groups=groups, **kw)
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where, bare_if_empty=always)}</div>
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where, bare_if_empty=True)}</div>
{results(recs, groups=groups, finder=True, **kw)}""")
@@ -549,7 +553,7 @@ def key(official=True):
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False, top=3,
ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None):
ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None, season=False):
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
Every list carries the same "Sort by" control. The rows are written in
@@ -558,6 +562,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
finder: a list driven by the filter bar over it (listing(): live count, empty state).
every: the list holds every trail (the home page's).
season: show each row's season (a month's list), as app.js does when a month is chosen.
groups: [(heading, trails, extra_fn)] to list the trails under headings (level `top`);
sorting is within each group and the groups keep their order. A heading may be a pair
(heading HTML, intro HTML): the intro is a sentence under the heading (an author's summary).
@@ -638,18 +643,14 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
tools = sort_select(default_sort, saved=saved, ranked=ranked, wholly=wholly)
dflt = SAVED_ORDER[0] if saved else "rank" if ranked else HERE_ORDER if wholly else default_sort
finder_attr = " data-finder" if finder else ""
# Under the count, while a month is chosen: how many trails are left out for having no season on
# file, and a way to see them (app.js fills it in from the rows, the same ones the list is).
unseasoned = ('\n <p class="results-note" data-unseasoned hidden><span data-unseasoned-text></span> '
'<button class="results-note__show" type="button" data-unseasoned-show>Show them</button></p>'
if finder else "")
return Markup(f"""<div class="results"{finder_attr} data-sortable data-default-sort="{esc(dflt)}">
season_attr = " data-season-shown" if season else ""
return Markup(f"""<div class="results"{finder_attr}{season_attr} data-sortable data-default-sort="{esc(dflt)}">
<div class="results-head">
{count}
<div class="results-tools">
{tools}
</div>
</div>{unseasoned}
</div>
{key(official=not only_routes)}
{list_head(default_sort)}{lists}{empty}
</div>""")
@@ -866,8 +867,25 @@ def description(records):
return common.cut_at_word(text, common.DESCRIPTION_LIMIT)
def render(records, site, repo_root=""):
"""The home page body (HTML). repo_root: where collections.toml names the lists the page shows."""
# How the home page's line names each kind of place, and where on the Places hub it goes.
PLACE_WAYS_IN = {"park": "park", "range": "mountain range", "wilderness": "wilderness area"}
def places_line(place_kinds):
"""The line below the rows that leads to the Places hub's sections: "Browse by park, by mountain
range or by wilderness area." for the kinds that have pages (place_kinds: kind keys), else ""."""
from . import places # imported here: places.py is the registry, and loads datafiles like this module
links = [f'by <a href="/regions/#{places.KINDS[k].segment}">{PLACE_WAYS_IN[k]}</a>'
for k in places.KINDS if k in place_kinds]
if not links:
return ""
text = links[0] if len(links) == 1 else ", ".join(links[:-1]) + " or " + links[-1]
return f'<p class="finder__foot finder__places">Browse {text}.</p>'
def render(records, site, repo_root="", place_kinds=()):
"""The home page body (HTML). repo_root: where collections.toml names the lists the page shows.
place_kinds: the kinds of place (olt/places.py) that have pages; the page then ends with a line to them."""
c = counts(records)
recs = sorted(records, key=sort_name)
total = c["total"]
@@ -893,6 +911,7 @@ def render(records, site, repo_root=""):
{browse_view(listing, overview_map(records, "Map of the trails the filters leave", scope="all"))}
<div class="finder__notes">
<p class="finder__foot">Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail&rsquo;s own maps before you go.</p>
{places_line(place_kinds)}
{contribute}
</div>
</div>"""
+1 -1
View File
@@ -130,7 +130,7 @@ def _render_site(records, out_dir, repo_root, site=None):
image=card, image_alt=card_alt))
dates[path] = seo.modified(rec)
pages += 1
body = home.render(records, site, repo_root)
body = home.render(records, site, repo_root, place_kinds={i["kind"] for i in place_infos.values()})
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site,
description=home.description(records),
jsonld=seo.home_jsonld(site)))
+1 -1
View File
@@ -105,7 +105,7 @@ def page(p, records, site, all_pages):
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where=""), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where="", season=lst.group == "month"), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
about=summary.facts(recs, records, place=(name, [info["key"]])), about_title=f"About these trails in {name}")}
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
{nav}
+1 -1
View File
@@ -75,7 +75,7 @@ def _kind():
kicker=_kicker, crumbs=_crumbs, lede=_lede, where="all", wholly=False,
facts_place=lambda info: (_in_name(info), ()), title_options=_title_options,
description=_description, box=lambda info: info.get("box"), nav=_nav,
in_name=_in_name, phrase=_phrase, always_filters=True)
in_name=_in_name, phrase=_phrase)
PARK = _kind()
+33 -2
View File
@@ -96,6 +96,33 @@ def verified(records):
return out
def _pct(share):
return f"{share * 100:.0f} percent"
def season_section(records, blind):
"""The paragraphs and table saying where seasons come from, how many trails have each kind, and how
the estimates did in the blind test (read from tools/season_blind_test.json, never typed)."""
n = len(records)
kinds = collections.Counter(facets.season_kind(r) for r in records)
basis = collections.Counter(facets.season_basis(r) for r in records if facets.season_kind(r) == "stated")
rows = [["The body that manages the trail, its association, or for a route its author", str(basis["primary"])],
["Two or more pages from different publishers that agree", str(basis["sources"])],
["One page", str(basis["source"])],
["Pages that differ, so set by judgement from all of them", str(kinds["judged"])],
["No page states one, so estimated from the climate and similar trails", str(kinds["estimated"])],
["All trails", str(n)]]
out = [f"""<p>Every trail has a season. Where a page states one, the season is that page&rsquo;s. Where the pages that state one differ and none is the trail&rsquo;s holder, its association or its route&rsquo;s author, the season is set by judgement from all of them and the climate, and the page says so. Where no page states one, the season is estimated from the climate at the trail&rsquo;s elevation and from similar trails: it reads &ldquo;About&rdquo; with a note, is marked in lists and is left out of the data search engines read. An estimated season is the usual window, not a closure, and an estimate is replaced when a page that states a season is found.</p>
{pagekit.table(["Where a trail's season comes from", "Trails"], rows, caption="Where the seasons come from", numeric=(1,))}"""]
if blind:
by = blind["by_confidence"]
conf = ", ".join(f"{name} {by[name]['matched']} of {by[name]['tested']} ({_pct(by[name]['share'])}) and "
f"{by[name]['strict_matched']} ({_pct(by[name]['strict_share'])})"
for name in ("high", "medium", "low") if by[name]["tested"])
out.append(f"""<p>How the estimates were tested. On {esc(blind["date"])} the method was run blind on {blind["tested"]} trails whose seasons a page does state, with those seasons hidden. Two measures are given together. {blind["matched"]} of {blind["tested"]} ({_pct(blind["share"])}) had their first and last months within a month of the page&rsquo;s; {blind["strict_matched"]} ({_pct(blind["strict_share"])}) also had no wrong gap in the middle, so the second measure counts a season with a gap that the page does not have, or without one that it has, as a miss. By the confidence it gave each estimate, first and last months and then also no wrong gap: {esc(conf)}. This measures how the method did where the answer is known, not a promise for any one trail.</p>""")
return "\n ".join(out)
def method_page(records, site, repo_root):
"""(title, description, body) for /method/."""
meaning = schema_meanings(repo_root)
@@ -120,12 +147,15 @@ def method_page(records, site, repo_root):
(a, b), (c, d_) = facets.PACE_KM, facets.PACE_KM_CROSS
coverage = []
for label, fn in (("A usual time stated by a source", lambda r: not facets.time_days(r)[2]),
("A season", lambda r: bool(facets.months(r))), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
("A season a page states", lambda r: facets.season_kind(r) == "stated"),
("A season set from pages that differ", lambda r: facets.season_kind(r) == "judged"),
("A season estimated from the climate and similar trails", lambda r: facets.season_kind(r) == "estimated"), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
("Terrain", lambda r: bool(facets.terrain(r))), ("What the walking is", lambda r: bool(facets.walking(r))),
("A computed climb that covers the whole trail", lambda r: facets.row_climb_m(r) is not None),
("A track included here", common.has_line)):
have = sum(1 for r in records if fn(r))
coverage.append([label, str(have), str(n - have)])
season_html = season_section(records, datafiles.blind_test(repo_root))
rows = [[label, str(k), f"{k / len(ver) * 100:.0f}%" if ver else ""] for label, k in bands]
body = (pagekit.head("How the figures are measured", (
f"What each figure on this site means, and how far to trust it. {len(ver)} of the {n} trails have a track whose "
@@ -145,7 +175,8 @@ def method_page(records, site, repo_root):
<p>Climb is the total ascent along the track.{(" It uses " + esc(model) + ", sampled every " + words.fmt_int(spacing) + " metres, with " + esc(smoothing[:1].lower() + smoothing[1:]) + ".") if model and spacing else ""} {esc(limits_text)}</p>
<p>A climb is ranked or shown in a list only where its track covers the whole trail: a track that covers part of the trail, or more than the trail, would mislead.</p>
<h2>Season and high point</h2>
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} Not every record has them, so a page built from them says how many records it covers.</p>
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} </p>
{season_html}
<h2>What the records have</h2>
{pagekit.table(["Figure", "Records with it", "Records without"], coverage, caption="How many records carry each figure", numeric=(1, 2))}
<p>Every fact is read on a page that the record names. See the <a href="/sources/">sources</a>, the <a href="/data/schema/">record schema</a> and <a href="{GLOSSARY}">the glossary</a>.</p>
+12 -6
View File
@@ -168,6 +168,7 @@ def regions_index_page(records, site, infos=()):
place_infos = list(infos.values()) if isinstance(infos, dict) else list(infos or ())
blocks = ""
jump = []
kinds = []
for g, name, keys in facets.PLACE_GROUPS:
infos = sorted((by_slug[k.lower()] for k in keys if k.lower() in by_slug), key=lambda i: i["name"])
if not infos:
@@ -200,7 +201,7 @@ def regions_index_page(records, site, infos=()):
f'<li><a href="{esc(i["path"])}">{esc(i["name"])}</a>'
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
for i in mine)
jump.append(f'<li><a href="#{esc(kind.segment)}">{esc(kind.hub_title)}<span class="lists-row__n">{len(mine)}</span></a></li>')
kinds.append(f'<li><a href="#{esc(kind.segment)}">{esc(kind.hub_title)} <span class="places-jump__n">{len(mine)}</span></a></li>')
blocks += f"""<section class="places__group" aria-labelledby="{esc(kind.segment)}">
<h2 id="{esc(kind.segment)}">{esc(kind.hub_title)}</h2>
<ul class="places__list">{rows}</ul>
@@ -214,12 +215,18 @@ def regions_index_page(records, site, infos=()):
foot = f'\n<div class="container"><p class="places__sum">Places with no listed trail: {links}.</p></div>'
n_us = sum(1 for r in records if "US" in common.countries(r))
n_ca = sum(1 for r in records if "CA" in common.countries(r))
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
# One compact row at the very top, whatever the screen: the states and provinces and each kind of
# place that has pages, each with its exact number of pages.
row = (f'<nav class="places-jump" aria-label="Jump to a kind of place"><ul>'
f'<li><a href="#states-and-provinces">States and provinces <span class="places-jump__n">{len(by_slug)}</span></a></li>'
f'{"".join(kinds)}</ul></nav>') if kinds else ""
body = f"""<div class="page-head"><div class="container">{row}<header class="titleblock">
<div class="titleblock__text"><h1>Places</h1>
<p class="page-head__lede">The {len(records)} trails by state and province, grouped into parts of the
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one&rsquo;s page.{lede_more}</p>
</div></header>
<nav class="lists-row" aria-label="Jump to a part of the country{" or a kind of place" if place_infos else ""}"><ul>{"".join(jump)}</ul></nav></div></div>
<nav class="lists-row" aria-label="Jump to a part of the country"><ul>{"".join(jump)}</ul></nav></div></div>
<span id="states-and-provinces"></span>
<div class="container section places">{blocks}</div>{foot}"""
description = (f"Where the {len(records)} long trails and routes are: {n_us} in the United States and {n_ca} in Canada, "
f"by state and province, with the number in each.")
@@ -309,7 +316,6 @@ class PageKind:
nav: object
in_name: object = None
phrase: object = None
always_filters: bool = False # the filter bar whatever the number of trails
def _state_kicker(info):
@@ -433,7 +439,7 @@ def place_page(info, records, site, kind, *, facet_pages=(), place_links=""):
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly, always=kind.always_filters), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
{home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
about=f"{summary.facts(recs, records, place=place)}{summary.details(recs)}",
about_title=f"About the trails {phrase}")}
{nav}{place_links}
@@ -526,7 +532,7 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead),
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead, season=lst.group == "month"),
home.overview_map(recs, f"Map of the trails in the list {lst.title}"),
about=f"{about}{before}{f'<p>{esc(note.strip())}</p>' if note else ''}<p class=\"finder__foot\">{rule}</p>",
about_title="About this list")}
+2 -1
View File
@@ -290,7 +290,8 @@ def _properties(rec):
props.append(_pv("Shape", facets.SHAPES[shape]))
props.append(_pv("Start", h.get("start", "")) if h.get("start") else None)
props.append(_pv("End", h.get("end", "")) if h.get("end") else None)
props.append(_pv("Usual season", h["season"]) if h.get("season") else None)
# Only a season a page states: an estimate is not a fact about the trail to hand to a search engine.
props.append(_pv("Usual season", h["season"]) if h.get("season") and not facets.season_estimated(rec) else None)
if common.is_route(rec):
route = rec.get("route", {})
props.append(_pv("Route author", route["creator"]) if route.get("creator") else None)
+4 -1
View File
@@ -45,14 +45,17 @@ def time_cell(rec):
def season_cell(rec):
return facets.season_text(rec) or "Not on file"
return facets.season_text(rec)
def figures_note(recs):
"""What the times and climbs of these trails mean, with the caveats the records state."""
est = sum(1 for r in recs if facets.time_days(r)[2])
unstated = [r for r in recs if facets.season_estimated(r)]
parts = [f"Times that start with “About” are estimated from the length ({est} of these). "
"Otherwise a source states the time.",
(f"Seasons that start with “About” are not stated by a page ({len(unstated)} of these): "
f"{facets.season_unstated_clause(unstated)}." if unstated else ""),
climb_caveat(recs)]
return " ".join(p for p in parts if p)
+3 -1
View File
@@ -148,7 +148,9 @@ def detail(rec):
out.append(f"Its high point is {esc(name + ', ') if name else ''}{words.elevation(m)}.")
season = facets.season_text(rec)
if season:
out.append(f"Season: {esc(season)}.")
how = (", judged from pages that differ" if facets.season_pages_differ(rec)
else ", estimated from the climate and similar trails" if facets.season_estimated(rec) else "")
out.append(f"Season: {esc(season)}{how}.")
rest = _rest_of_summary(rec)
if rest:
out.append(f'<span class="record-text">{esc(rest)}</span>')
+18 -6
View File
@@ -303,6 +303,7 @@ def _name_html(rec):
MAX_BRIEF = 4 # sentences in the "In brief" paragraph
PINNED = -1 # the priority of a sentence that is kept besides those (an estimated season)
MONTH_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
SEASON_WORDS = ("spring", "summer", "fall", "autumn", "winter", "late", "early", "mid", "from", "about")
SENTENCE_VERBS = re.compile(r"\b(is|are|can|start|starts|hikes?|hiked|travelled|traveled|bring|brings|closed|best)\b", re.I)
@@ -313,6 +314,13 @@ def season_sentence(rec):
seasons, ("sentence", "Northbound hikes start late February to early April") for one the record
already words as a sentence, or None when the record has none or it is too long to say briefly.
The caller adds the full stop. Only the record's own words are used."""
if facets.season_estimated(rec):
# Never worded as a fact, and never joined to the GPX clause with "and".
phrase = facets.season_phrase(rec).rstrip(". ")
phrase = phrase.lower() if phrase.lower() == "all year" else phrase
if facets.season_pages_differ(rec):
return ("estimate", f"The pages differ on the season; it is judged to be about {phrase}")
return ("estimate", f"No source gives a season; the climate suggests about {phrase}")
text = facets.season_text(rec).strip().rstrip(". ")
if not text:
return None
@@ -452,19 +460,23 @@ def brief_sentences(rec):
# When to walk it and whether this site has a GPX: one sentence where the season is a plain range.
clause = gpx_clause(rec) or ("this site has no GPX for it" + _see_clause(rec))
season = season_sentence(rec)
if season and not re.search(r"[,;]", season[1]):
if season and season[0] != "estimate" and not re.search(r"[,;]", season[1]):
# "The usual season is May to July, and this page has a GPX of the track to download."
items.append((3, 5, f"{esc(season[1])}, and {esc(clause)}."))
else:
if season:
items.append((3.5, 5, esc(season[1]) + "."))
# An estimated season is always said, so it is never left for a reader to take as a fact
# by omission: it is the one sentence that may stand beyond MAX_BRIEF.
items.append((PINNED if season[0] == "estimate" else 3.5, 5, esc(season[1]) + "."))
items.append((3, 6, esc(clause[:1].upper() + clause[1:]) + "."))
permit = permit_sentence(rec)
if permit:
items.append((6, 7, esc(permit)))
# At most MAX_BRIEF sentences: the lowest priorities are kept, shown in reading order.
kept = sorted(sorted(items, key=lambda i: (i[0], i[1]))[:MAX_BRIEF], key=lambda i: i[1])
pinned = [i for i in items if i[0] == PINNED]
rest = sorted((i for i in items if i[0] != PINNED), key=lambda i: (i[0], i[1]))[:MAX_BRIEF]
kept = sorted(rest + pinned, key=lambda i: i[1])
return [text for _, _, text in kept]
@@ -646,7 +658,7 @@ def glance(rec, records=None, place_infos=()):
rows.append(glance_row(facets.TIME, facets.time_text(rec), time_note(rec, records)))
season = facets.season_text(rec)
if season:
rows.append(glance_row(facets.SEASON, season))
rows.append(glance_row(facets.SEASON, season, facets.season_note(rec)))
if facets.walking(rec):
walking = facets.WALKING_VALUES[facets.walking(rec)]
if facets.walking(rec) in facets.CROSS_COUNTRY:
@@ -718,7 +730,7 @@ def glance(rec, records=None, place_infos=()):
unfinished = ""
if h.get("unfinished"):
unfinished = f'<p class="glance__warn"><strong>Not finished.</strong> {common.rich(common.sentence(h["unfinished"]))}</p>'
missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain),
missing = [name for name, have in ((facets.TERRAIN, terrain),
(facets.WALKING, facets.walking(rec)),
(PERMITS, h.get("permit"))) if not have]
pending = ""
@@ -1581,7 +1593,7 @@ def hike_sources_block(rec):
for src in hike.sources(rec):
url = src.get("url", "")
who = src.get("publisher") or (host(url) if url else "Source")
facts_ = [words.HIKE_FACTS.get(f, f) for f in src.get("facts", [])]
facts_ = list(dict.fromkeys(words.HIKE_FACTS.get(f, f) for f in src.get("facts", []))) # season and months read alike
what = ("For " + words.join_names(facts_)) if facts_ else ""
link = ext_link(url, who) if url else esc(who)
detail = " · ".join(x for x in (host(url) if url else "", what) if x)