Say what each page is in the words people search with, and mark up the facts
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

A whole-site search audit found clean foundations and three gaps: titles
without the words people search for, no structured data on trail pages,
and trails that did not link to each other.

- Trail titles carry the name hikers use, the abbreviation, the length
  and what the page offers; "GPX" only where the page has one. A new
  optional `common_name` field holds the name hikers use (13 records).
- Descriptions are built from each record, at most 155 characters.
- Place and list pages are titled for what they are; heading levels no
  longer jump.
- Trail pages link to similar and related trails and to the lists they
  belong to. Every trail has at least three links from other trails.
- JSON-LD on every page: a Place for each trail, breadcrumbs, item lists
  on list and place pages, WebSite and Organization on the home page, a
  fuller Dataset on the data page.
- A social card per trail, a changelog feed, `lastmod` in the sitemap from
  record dates, `noindex` on the 404 and on raw per-trail files, a
  favicon and an `llms.txt` listing the data files and licences.
- The "Considered and left out" page has its spacing fixed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-16 14:57:30 -07:00
1 parent a46338afd5
commit 5b80fccd1e
245 files changed
+2534 -137

No files matched your search

+25 -12
View File
@@ -37,6 +37,12 @@ class List:
# The order the list opens in, a key of facets.SORTS. Name order unless
# the list is defined by an order (the longest, the shortest, a week).
sort: str = "name"
# The page's <title> before the site name, in the words people search with; {n} is
# the number of trails. Empty: the list's own title with the count.
page_title: str = ""
def search_title(self, n):
return (self.page_title or f"{self.title}: {{n}} Trails").format(n=n)
def _km(mi):
@@ -47,39 +53,46 @@ def _band(key):
return lambda r: facets.time_band(r) == key
# The terrain as an adjective, for a list's page title ("Coastal Hiking Trails").
TERRAIN_ADJECTIVE = {"coast": "Coastal", "lakes": "Lake"}
LISTS = (
List("national-scenic-trails", "National Scenic Trails",
"The long trails the United States Congress has named National Scenic Trails.",
facets.is_national),
facets.is_national, page_title="National Scenic Trails: {n} Long Hiking Trails"),
List("routes", "Routes", facets.ROUTE_DEFINITION,
lambda r: facets.kind(r) == "route"),
lambda r: facets.kind(r) == "route", page_title="Long Hiking Routes by Author: {n} Routes"),
List("longest", "The longest",
f"Trails of {LONG_MI:,} miles ({_km(LONG_MI)} km) or more.",
lambda r: r["length_km"] >= LONG_KM, sort="length-desc"),
lambda r: r["length_km"] >= LONG_KM, sort="length-desc",
page_title=f"Longest Hiking Trails: {{n}} Trails of {LONG_MI:,}+ Miles"),
List("under-100-miles", f"Under {SHORT_MI} miles",
f"Trails shorter than {SHORT_MI} miles ({_km(SHORT_MI)} km).",
lambda r: r["length_km"] < SHORT_KM, sort="length-asc"),
lambda r: r["length_km"] < SHORT_KM, sort="length-asc",
page_title=f"Hiking Trails Under {SHORT_MI} Miles: {{n}} Long Trails"),
List("a-week-or-less", "A week or less",
"Trails most people walk in a week or less, as a source states it or as estimated from the length.",
_band("week"), sort="time-asc"),
_band("week"), sort="time-asc", page_title="Long Trails to Hike in a Week or Less: {n} Trails"),
List("one-to-two-weeks", "One to two weeks",
"Trails that take one to two weeks, as a source states it or as estimated from the length.",
_band("two-weeks"), sort="time-asc"),
_band("two-weeks"), sort="time-asc", page_title="Long Trails to Hike in One to Two Weeks: {n} Trails"),
List("loops", "Loops", "Trails that finish where they start.",
lambda r: facets.shape(r) == "loop"),
lambda r: facets.shape(r) == "loop", page_title="Loop Hiking Trails: {n} Long Trail Loops"),
List("with-gpx", "With a GPX to download",
"Trails with a GPX file of the track on their page.",
facets.gpx_here),
facets.gpx_here, page_title="Long Trails with a GPX to Download: {n} Trails"),
List("canada", "In Canada", "Trails in Canada, or crossing into it.",
lambda r: "CA" in common.countries(r)),
lambda r: "CA" in common.countries(r), page_title="Hiking Trails in Canada: {n} Long Trails"),
List("united-states", "In the United States", "Trails in the United States, or crossing into it.",
lambda r: "US" in common.countries(r)),
lambda r: "US" in common.countries(r), page_title="Hiking Trails in the United States: {n} Long Trails"),
List("off-trail", "Cross-country",
"Trails with stretches of walking where there is no trail.",
lambda r: facets.walking(r) in facets.CROSS_COUNTRY),
lambda r: facets.walking(r) in facets.CROSS_COUNTRY,
page_title="Cross-Country Hiking: {n} Long Trails and Routes"),
) + tuple(
List(f"terrain-{t}", label, f"Trails with {t} among their main terrain.",
lambda r, t=t: t in facets.terrain(r))
lambda r, t=t: t in facets.terrain(r),
page_title=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails: {{n}} Long Trails")
for t, label in words.TERRAIN.items()
)
+75
View File
@@ -0,0 +1,75 @@
"""Per-trail social cards (1200 x 630 PNG), the image link previews show for a trail page.
web/cards/<id>.png is made by web/tools/make_cards.py and committed, the way
the logo thumbnails are (olt/thumbs.py): the site build is standard library
only and draws nothing. The pages step copies each card to trails/<id>/card.png.
A trail with no card file falls back to the site card, with a warning.
"""
import hashlib
import os
import shutil
import struct
import sys
from . import facets, words
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CARD_DIR = os.path.join(WEB_DIR, "cards")
CARD_NAME = "card.png"
def prepare(rec, out_dir, card_dir=CARD_DIR):
"""Copy the record's card next to its page. Returns (site path, alt text), or ("", "")
when there is none, which leaves the page on the site card."""
tid = rec["id"]
dest = os.path.join(out_dir, "trails", tid, CARD_NAME)
src = os.path.join(card_dir, f"{tid}.png")
if not os.path.isfile(src):
print(f"warning: {tid}: no card at {os.path.relpath(src, WEB_DIR)}; the page uses the site card "
f"(run web/tools/make_cards.py)", file=sys.stderr)
if os.path.isfile(dest):
os.remove(dest)
return "", ""
os.makedirs(os.path.dirname(dest), exist_ok=True)
shutil.copyfile(src, dest)
return f"/trails/{tid}/{CARD_NAME}", f"{rec['name']}: its track, and its length in miles and kilometres"
def card_name(rec):
"""The name a card shows: the one hikers use where the record has it."""
return rec.get("common_name") or rec["name"]
def where(rec):
"""The places a card shows: up to three names, else a count."""
names = [facets.place_name(k) for k in facets.place_keys(rec)]
return ", ".join(names) if len(names) <= 3 else f"{len(names)} states and provinces"
def lines(rec):
"""The three texts a card shows: its name, its length in miles and kilometres, its places."""
return (card_name(rec),
f"{words.fmt_int(rec['derived']['length_mi'])} miles · {words.fmt_int(rec['length_km'])} km",
where(rec))
def fingerprint(rec):
"""A short hash of what a card shows. make_cards.py stores it in the PNG (text chunk
"olt-card"), and a test compares it, so a record that changes shows up as a stale card."""
return hashlib.sha1("\n".join(lines(rec)).encode("utf-8")).hexdigest()[:12]
def stored_fingerprint(path):
"""The "olt-card" text chunk of a card file, or ""."""
with open(path, "rb") as f:
data = f.read()
pos = 8
while pos + 8 <= len(data):
size, kind = struct.unpack(">I4s", data[pos:pos + 8])
body = data[pos + 8:pos + 8 + size]
if kind == b"tEXt" and body.startswith(b"olt-card\x00"):
return body.split(b"\x00", 1)[1].decode("latin-1")
if kind == b"IEND":
break
pos += 12 + size
return ""
+28
View File
@@ -50,6 +50,34 @@ def partial_short_text(rec):
f"{words.length(rec['length_km'], mi=rec['derived']['length_mi'])} published")
# A search result shows about this much. The title limit counts the whole title,
# the site name included.
TITLE_LIMIT = 65
DESCRIPTION_LIMIT = 155
def title_room(site):
"""How many characters a page's own title may have, before " · <site name>"."""
return TITLE_LIMIT - len(site.name) - len(" \u00b7 ")
def fit_title(options, site):
"""The first of options (richest first) that fits title_room; else the last, the shortest."""
return next((o for o in options if len(o) <= title_room(site)), options[-1])
def plain_name(rec):
"""The name hikers use (common_name) where the record has one, else its name. Plain text."""
return rec.get("common_name") or rec["name"]
def cut_at_word(text, limit):
"""text if it fits, else cut at a word with an ellipsis, within limit characters."""
if len(text) <= limit:
return text
return text[:limit - 1].rsplit(" ", 1)[0].rstrip(" ,;:.") + "\u2026"
def name(rec):
"""The record's name as HTML text, marked with its language when it is not
English (web/site.toml [name_lang], copied to derived.name_lang by pages.py).
+19 -6
View File
@@ -215,7 +215,10 @@ def sources_page(records, site, repo_root):
f'<p class="page-head__lede">Where the tracks come from, and the terms each source states.</p>'
f'</div></header></div></div>{computed}'
f'<div class="container section"><div class="prose doc">{doc_html}</div></div>')
return "Sources", "Where each trail track comes from: licences, track sources and source terms.", Markup(body)
n_tracks = sum(1 for r in records if r.get("source", {}).get("line_file"))
description = (f"Where the tracks and facts for the {len(records)} trails come from: {n_tracks} tracks included, "
f"each source's licence and terms, and the credit each asks for.")
return "Sources and Licences for Trail Tracks and Data", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
def logos_page(records, site, repo_root):
@@ -254,7 +257,10 @@ their own (<code class="raw">no-logo-exists</code>): the pages that would show o
{counts["logo-not-found"]} have an emblem, or may have one, but no usable artwork of it was found at a source the
dataset allows (<code class="raw">logo-not-found</code>). Each record says in its logo note where an emblem was
looked for.</p></div>"""
return "Logos", "Trail logos, their holders, and how a holder can ask for removal.", Markup(body)
n_logos = sum(1 for r in records if "shield" in r["derived"]["files"])
description = (f"The {n_logos} trail logos shown on {site.name}, who holds each one, "
f"and how a holder can ask for a logo to be removed.")
return "Trail Logos and Their Holders", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
BREAD = Markup('<nav class="breadcrumb" aria-label="Breadcrumb"><ol><li><a href="/about/">About</a></li>')
@@ -375,7 +381,9 @@ a source page, a map, or a measured track.</p>
{contrib}
</section>
</div></div>"""
return "About", f"What {site.name} is, how trails are chosen, the data and its sources, and how to correct or add a trail.", Markup(body)
description = (f"{n} trails and routes in the United States and Canada: how a trail is chosen, "
f"where the data comes from, and how to correct or add one.")
return "About: How Trails Are Listed and Checked", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
def _size(out_dir, relpath):
@@ -490,7 +498,9 @@ def data_page(records, site, repo_root, out_dir):
<li><a href="/sources/">Sources</a><small>Each source, its terms and the trails that use it</small></li>
</ul></div>
</div>"""
return "Data", "Bulk downloads, stable per-trail file URLs, the record schema and licences.", Markup(body)
description = (f"Download the records of all {len(records)} trails, and every track that may be shared, "
f"as CSV, JSON, GeoJSON and GPX. The records are public domain.")
return "Trail Data Downloads: CSV, JSON, GeoJSON and GPX", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
def schema_page(site, repo_root):
@@ -501,7 +511,9 @@ def schema_page(site, repo_root):
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
<h1>Record schema</h1></div></header></div></div>
<div class="container section"><div class="prose doc">{doc_html}</div></div>"""
return "Record schema", "Every field of a trail record (trail.toml) and what it means.", Markup(body)
return ("Trail Record Schema: Every Field of trail.toml",
"What each field of a trail record means, which fields need a source and a history entry, "
"and how the elevation figures are computed.", Markup(body))
def changelog_page(site, repo_root):
@@ -512,7 +524,8 @@ def changelog_page(site, repo_root):
<header class="titleblock"><div class="titleblock__text"><p class="kicker">Reference</p>
<h1>Changelog</h1></div></header></div></div>
<div class="container section"><div class="prose doc">{doc_html}</div></div>"""
return "Changelog", "What changed in the dataset, release by release.", Markup(body)
return ("Changelog: What Changed in the Trail Data",
"Trails added, removed and corrected in the dataset, release by release, newest first.", Markup(body))
def copy_licences(out_dir, repo_root):
+86
View File
@@ -0,0 +1,86 @@
"""The Atom feed of the changelog: /feed.xml.
One entry for each dated heading of CHANGELOG.md ("## 2026-11-16 - What changed"),
newest first, as many as FEED_MAX. An entry's date is its heading's date, never
the build date, so the feed changes only when the changelog does. Each entry links
to its heading on /data/changelog/ and carries the section as HTML.
No author is named: site.toml names none, so the feed's author is the site.
"""
import html
import os
import re
from . import docs, md
FEED_MAX = 30
HEADING = re.compile(r"^(\d{4}-\d{2}-\d{2})\s*[-:–]\s*(.+)$")
def entries(text):
"""[(date, title, slug, markdown body)] for the changelog's dated sections, in file order."""
slugs = [slug for level, _, slug in md.headings(text) if level == 2]
out = []
for (heading, body), slug in zip(md.split_sections(text, level=2), slugs):
m = HEADING.match(heading)
if m:
out.append((m.group(1), m.group(2).strip(), slug, body))
return out
def newest_date(text):
"""The newest date in the changelog, or ""."""
return max((e[0] for e in entries(text)), default="")
def atom(text, site):
"""The Atom document for a changelog's text; "" when the site has no base_url."""
if not site.base_url:
return ""
base = site.base_url
def absolute(href):
return base + href if href.startswith("/") else href
rewrite = docs.make_link_rewrite(site)
def link_rewrite(href):
target = rewrite(href)
return absolute(target) if target else target
found = entries(text)[:FEED_MAX]
q = lambda s: html.escape(s, quote=True) # noqa: E731
rows = []
for date, title, slug, body in found:
content = md.render(body, heading_offset=2, link_rewrite=link_rewrite)
url = f"{base}/data/changelog/#{slug}"
rows.append(
f" <entry>\n <title>{q(title)}</title>\n <id>{q(url)}</id>\n"
f' <link rel="alternate" type="text/html" href="{q(url)}"/>\n'
f" <updated>{date}T00:00:00Z</updated>\n"
f' <content type="html">{q(content)}</content>\n </entry>\n')
updated = f"{max((e[0] for e in found), default='1970-01-01')}T00:00:00Z"
return ('<?xml version="1.0" encoding="utf-8"?>\n'
'<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">\n'
f" <title>{q(site.name)}: what changed</title>\n"
f" <subtitle>{q(site.tagline)}</subtitle>\n"
f" <id>{q(base)}/feed.xml</id>\n"
f' <link rel="self" type="application/atom+xml" href="{q(base)}/feed.xml"/>\n'
f' <link rel="alternate" type="text/html" href="{q(base)}/data/changelog/"/>\n'
f" <updated>{updated}</updated>\n"
f" <author><name>{q(site.name)}</name></author>\n"
f"{''.join(rows)}</feed>\n")
def write_feed(out_dir, site, repo_root):
"""Write feed.xml from the changelog. Returns its path, or "" when there is no base_url."""
text = docs.read_doc(repo_root, "CHANGELOG.md")
xml = atom(text, site)
path = os.path.join(out_dir, "feed.xml")
if not xml:
if os.path.isfile(path):
os.remove(path)
return ""
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(xml)
return path
+18 -6
View File
@@ -135,7 +135,8 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False):
"""
route = facets.kind(rec) == "route"
lo, hi, est = facets.time_days(rec)
search = " ".join([rec["name"], rec.get("short_name", ""), rec["id"], facets.author(rec)]).lower()
search = " ".join([rec["name"], rec.get("common_name", ""), rec.get("short_name", ""), rec["id"],
facets.author(rec)]).lower()
abbr = rec.get("short_name", "")
abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh"
abbr_html = f' <span class="{abbr_cls}">{esc(abbr)}</span>' if abbr else ""
@@ -409,7 +410,7 @@ def key(official=True):
</ul>"""
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False):
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False, top=3):
"""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
@@ -417,8 +418,11 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
JavaScript off; app.js reorders in place and keeps ?sort= in the address.
finder: the home page's list, driven by the filters (live count, empty state).
groups: [(heading, trails, extra_fn)] to list the trails under level-3 headings;
groups: [(heading, trails, extra_fn)] to list the trails under headings (level `top`);
sorting is within each group and the groups keep their order.
top: the heading level of a trail's name where the trails are not in groups (and of a
group's heading where they are; the names then sit one level lower). 3 under a page's
own h2 (the home page); 2 on a page whose h1 is followed directly by the list.
extra_fn(rec) gives HTML placed last in each row.
routes_list: passed to entry() for the Routes list (see there).
saved: the Saved page's list. Every trail's row is written hidden, and
@@ -441,11 +445,11 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
lists = ""
every = ' data-every-trail' if finder or saved else ""
for heading, items, extra_fn in groups:
level = 4 if heading else 3
level = top + 1 if heading else top
rows = "\n".join(entry(r, level=level, extra=extra_fn(r) if extra_fn else "",
routes_list=routes_list, hidden=saved) for r in items)
if heading:
lists += f'\n <h3 class="results__group">{heading}</h3>'
lists += f'\n <h{top} class="results__group">{heading}</h{top}>'
list_id = ' id="entries"' if finder else ""
lists += f'\n <ol class="entries"{list_id}{every}>\n{rows}\n </ol>'
if finder:
@@ -586,6 +590,14 @@ def lists_row(records):
</nav>"""
def description(records):
"""The home page's meta description: how many, what each has, and how many have a GPX."""
n_gpx = sum(1 for r in records if facets.gpx_here(r))
text = (f"{len(records)} long-distance hiking trails and routes in the US and Canada: length, typical time, "
f"a source for every fact, and a GPX for {n_gpx}.")
return common.cut_at_word(text, common.DESCRIPTION_LIMIT)
def render(records, site):
"""The home page body (HTML)."""
c = counts(records)
@@ -600,7 +612,7 @@ def render(records, site):
f'<a href="{esc(site.new_trail_url)}">suggest a trail</a>.</p>')
return f"""<section class="hero hero--short hero--home" aria-labelledby="hero-title">
<div class="container hero__inner">
<h1 id="hero-title" class="lockup"><img class="lockup__mark" src="/assets/favicon.svg" alt="" width="96" height="96">{esc(site.name)}</h1>
<h1 id="hero-title" class="lockup"><img class="lockup__mark" src="/assets/favicon.svg" alt="" width="96" height="96">{esc(site.name)}<span class="vh">: long-distance hiking trails of the United States and Canada</span></h1>
<p class="hero__tagline">Long-distance hiking trails of the United States and Canada.</p>
<ul class="hero__tags">
<li><a href="#finder">Filters</a></li>
+45 -9
View File
@@ -18,7 +18,7 @@ scripts or styles (the Content-Security-Policy forbids them).
import json
import os
from . import common, site as site_settings
from . import common, seo, site as site_settings
from .markup import Markup, attrs, esc, json_block
NAV = (
@@ -33,6 +33,8 @@ NAV_PARENT = {"/trails/": "/", "/lists/": "/", "/routes/": "/",
"/sources/": "/about/", "/logos/": "/about/", "/data/": "/about/",
"/left-out/": "/about/"}
FEED_PATH = "/feed.xml" # the Atom feed of the changelog (olt/feed.py)
FONT_PRELOADS = (
"/assets/fonts/source-serif-4-latin.woff2",
"/assets/fonts/ibm-plex-sans-condensed-400-latin.woff2",
@@ -159,17 +161,37 @@ def footer(site):
def _ld_json_block(obj):
"""One JSON-LD script. "<", ">" and "&" are written as \\u escapes, so no text from a
record can close the script element or start a tag inside it."""
text = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
text = text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
return Markup(f'<script type="application/ld+json">{text}</script>')
def structured_data(jsonld, body, path, site, noindex=False):
"""The page's JSON-LD as one <script>, or "": the page's own nodes (one dict or a list of
them, from olt.seo) and a BreadcrumbList equal to the breadcrumb the body shows. A page
that is not indexed carries none."""
if noindex:
return ""
nodes = list(jsonld) if isinstance(jsonld, (list, tuple)) else ([jsonld] if jsonld else [])
crumb = seo.breadcrumb_node(body, site, path, seo.breadcrumb_id(site, path))
if crumb:
nodes.append(crumb)
if not nodes:
return ""
obj = {"@context": "https://schema.org", **nodes[0]} if len(nodes) == 1 else \
{"@context": "https://schema.org", "@graph": nodes}
return str(_ld_json_block(obj))
def layout(title, body, *, path, description="", maps=False, outdoor=False, scripts=(), data=None, site=None,
jsonld=None, og_type="website", noindex=False):
jsonld=None, og_type="website", noindex=False, image="", image_alt="", alternates=()):
"""Return a complete HTML document.
title the page's own title ("Arizona National Scenic Trail"); the site
name is appended. Empty for the home page: "<name>: <tagline>".
name is appended. Empty for the home page: site.toml's
home_title, or "<name>: <tagline>" where that is not set.
body the page content (HTML, Markup or str), placed inside <main>.
path the page's site path, e.g. "/regions/" (canonical link, nav state).
description meta description; defaults to the site tagline.
@@ -179,12 +201,18 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
scripts extra same-origin script URLs, loaded with defer after app.js.
data optional object, embedded as <script type="application/json" id="page-data">.
site settings (olt.site.Site); defaults to web/site.toml.
noindex True for a page whose content is the visitor's own (/saved/):
jsonld the page's own schema.org nodes, one dict or a list (olt.seo builds them
from the records). A BreadcrumbList for the breadcrumb in the body is added.
image site path of the page's social card (1200 x 630 PNG); the site card
/assets/og.png when empty. image_alt describes it.
alternates (href, media type, title) of other forms of this page, as <link rel="alternate">.
noindex True for a page whose content is the visitor's own (/saved/), or the 404 page:
search engines are asked not to index it, and it has no
canonical address (its address carries the list). seo.py
leaves it out of the sitemap.
"""
site = site or site_settings.load()
title = title or site.home_title
full_title = f"{title} · {site.name}" if title else f"{site.name}: {site.tagline}"
description = description or site.tagline
canonical = "" if noindex else site.canonical(path)
@@ -211,19 +239,27 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
head.append(f'<meta property="og:url" content="{esc(canonical)}">')
if site.base_url:
# A PNG: link previews (Reddit, Slack, iMessage) do not draw an SVG.
image = esc(site.canonical("/assets/og.png"))
head.append(f'<meta property="og:image" content="{image}">')
card = esc(site.canonical(image or "/assets/og.png"))
alt = esc(image_alt or site.name)
head.append(f'<meta property="og:image" content="{card}">')
head.append('<meta property="og:image:type" content="image/png">')
head.append('<meta property="og:image:width" content="1200">')
head.append('<meta property="og:image:height" content="630">')
head.append(f'<meta name="twitter:image" content="{image}">')
if jsonld is not None:
head.append(str(_ld_json_block(jsonld)))
head.append(f'<meta property="og:image:alt" content="{alt}">')
head.append(f'<meta name="twitter:image" content="{card}">')
head.append(f'<meta name="twitter:image:alt" content="{alt}">')
ld = structured_data(jsonld, body, path, site, noindex)
if ld:
head.append(ld)
head += [
'<meta name="color-scheme" content="light dark">',
'<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">',
'<link rel="icon" href="/assets/favicon-32.png" type="image/png" sizes="32x32">',
'<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">',
f'<link rel="alternate" type="application/atom+xml" title="{esc(site.name)}: what changed" href="{FEED_PATH}">',
]
head += [f'<link rel="alternate" type="{esc(kind)}" href="{esc(href)}"{attrs(title=name)}>'
for href, kind, name in alternates]
head += [f'<link rel="preload" href="{f}" as="font" type="font/woff2" crossorigin>' for f in FONT_PRELOADS]
if maps:
head.append(f'<link rel="stylesheet" href="{MAPLIBRE_CSS}">')
+3 -3
View File
@@ -135,10 +135,10 @@ def left_out_page(entries, site, repo_root):
<div class="titleblock__text"><h1>Considered and left out</h1>
<p class="page-head__lede">Trails and routes that were looked at for this dataset and left out, and why.</p>
</div></header></div></div>
<div class="container section">
<div class="container section section--finder place">
<p class="prose">{_opening(entries, site)}</p>
{groups}
</div>"""
description = ("Trails and routes considered for this dataset and left out: "
description = (f"{len(entries)} trails and routes considered for {site.name} and left out: "
"the reason, the deciding fact and its source page for each one.")
return "Considered and left out", description, Markup(body)
return "Trails Considered and Left Out, and Why", description, Markup(body)
+44 -19
View File
@@ -8,11 +8,15 @@ writes:
/trails/<id>/index.html one page per record
/trails/<id>/trail.toml the raw record; release.txt beside it where the trail has one
/trails/<id>/shield-thumb.png the list-size copy of a PNG logo (olt/thumbs.py)
/trails/<id>/card.png the trail's social card, from web/cards/ (olt/cards.py)
/regions/, /regions/<slug>/ Places: the hub and one page per state or province
/lists/, /lists/<key>/ the lists shown today (olt/browse.py); /routes/ is the Routes list
/about/ and the pages under it: /data/, /data/schema/, /data/changelog/, /sources/, /logos/, /left-out/
/saved/ the visitor's saved trails (olt/saved.py; not indexed)
/404.html not found
/404.html not found (not indexed)
/sitemap.xml, /robots.txt with a <lastmod> from the data (olt/seo.py)
/feed.xml the changelog as an Atom feed (olt/feed.py)
/llms.txt the bulk files, per-trail files and licences, as plain links
Adding a page elsewhere (regions, sources, ...): build its body as HTML,
wrap it with olt.layout.layout() and write it with olt.layout.write_page().
@@ -22,7 +26,7 @@ import json
import os
import shutil
from . import browse, docs, home, layout, leftout, regions, saved, seo, site as site_settings, thumbs, trail
from . import browse, cards, docs, facets, feed, home, layout, leftout, regions, saved, seo, site as site_settings, thumbs, trail
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
@@ -58,6 +62,7 @@ def copy_record_files(rec, out_dir, repo_root):
def not_found_page(site):
"""The 404 page. It is not for search results: noindex, and no canonical address."""
body = layout.page_head("Page not found", kicker="404",
lede="There is no page at this address. Search the trails by name instead.")
body += """<div class="container section">
@@ -68,7 +73,7 @@ def not_found_page(site):
</form>
<p class="prose"><a href="/">Find a trail</a> on the home page, or browse by <a href="/regions/">place</a>.</p>
</div>"""
return layout.layout("Page not found", body, path="/404.html", site=site)
return layout.layout("Page not found", body, path="/404.html", site=site, noindex=True)
def render_site(records, out_dir, repo_root, site=None):
@@ -76,6 +81,8 @@ def render_site(records, out_dir, repo_root, site=None):
site = site or site_settings.load()
copy_assets(out_dir)
pages = 0
dates = {} # page path -> its own date (YYYY-MM-DD), for the sitemap
everything = seo.newest(records)
for rec in records:
# Read by common.name() wherever a page shows the record's name as text.
rec["derived"]["name_lang"] = site.name_lang.get(rec["id"], "")
@@ -84,30 +91,41 @@ def render_site(records, out_dir, repo_root, site=None):
thumbs.prepare(rec, out_dir, repo_root)
title, description, body, needs_map = trail.render(rec, site, records)
path = f"/trails/{rec['id']}/"
layout.write_page(out_dir, path, layout.layout(title, body, path=path, description=description,
maps=needs_map, outdoor=needs_map, site=site))
card, card_alt = cards.prepare(rec, out_dir)
layout.write_page(out_dir, path, layout.layout(
title, body, path=path, description=description, maps=needs_map, outdoor=needs_map, site=site,
jsonld=seo.trail_jsonld(rec, site, title=title, description=description),
image=card, image_alt=card_alt))
dates[path] = seo.modified(rec)
pages += 1
dataset = seo.dataset_jsonld(records, site)
body = home.render(records, site)
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site, jsonld=dataset))
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site,
description=home.description(records),
jsonld=seo.home_jsonld(site)))
dates["/"] = everything
layout.write_page(out_dir, "/404.html", not_found_page(site))
pages += 2
def add(path, title, description, body_html, *, maps=False, jsonld=None):
def add(path, title, description, body_html, *, maps=False, jsonld=None, recs=None, date="", alternates=()):
"""Write a page. recs: the trails it lists, which give its date and its ItemList."""
nonlocal pages
if recs is not None:
jsonld = seo.collection_jsonld(path, site, title=title, description=description, recs=recs)
layout.write_page(out_dir, path, layout.layout(
title, body_html, path=path, description=description, maps=maps, site=site, jsonld=jsonld))
title, body_html, path=path, description=description, maps=maps, site=site, jsonld=jsonld,
alternates=alternates))
dates[path] = date or (seo.newest(recs) if recs is not None else everything)
pages += 1
t, d, b = regions.regions_index_page(records, site)
add("/regions/", t, d, b)
add("/regions/", t, d, b) # every trail is on it: the newest of them
by_slug, _ = regions.collect_regions(records)
region_paths = []
for slug in sorted(by_slug):
t, d, b, needs_map = regions.region_page(slug, records, site)
path = f"/regions/{slug}/"
region_paths.append(path)
add(path, t, d, b, maps=needs_map)
add(path, t, d, b, maps=needs_map, recs=by_slug[slug]["records"])
list_paths = []
shown = browse.shown(records)
for lst, recs in shown:
@@ -116,31 +134,38 @@ def render_site(records, out_dir, repo_root, site=None):
t, d, b, needs_map = regions.list_page(lst, recs, len(records), site)
path = browse.path(lst)
list_paths.append(path)
add(path, t, d, b, maps=needs_map)
add(path, t, d, b, maps=needs_map, recs=recs)
t, d, b = regions.lists_index_page(records, site)
add("/lists/", t, d, b)
t, d, b, needs_map = regions.routes_page(records, site, repo_root)
add("/routes/", t, d, b, maps=needs_map)
add("/routes/", t, d, b, maps=needs_map, recs=[r for r in records if facets.kind(r) == "route"])
t, d, b = docs.sources_page(records, site, repo_root)
add("/sources/", t, d, b)
t, d, b = docs.logos_page(records, site, repo_root)
add("/logos/", t, d, b)
t, d, b = docs.about_page(records, site, repo_root)
add("/about/", t, d, b)
changelog = feed.newest_date(docs.read_doc(repo_root, "CHANGELOG.md"))
t, d, b = docs.data_page(records, site, repo_root, out_dir)
add("/data/", t, d, b, jsonld=dataset)
add("/data/", t, d, b, jsonld=seo.dataset_jsonld(records, site, version=changelog),
alternates=[(f"/data/{name}", kind, f"{site.name}: {name}") for name, kind, _ in seo.distribution()[:2]])
t, d, b = docs.schema_page(site, repo_root)
add("/data/schema/", t, d, b)
add("/data/schema/", t, d, b, date=changelog)
t, d, b = docs.changelog_page(site, repo_root)
add("/data/changelog/", t, d, b)
t, d, b = leftout.left_out_page(leftout.load_entries(repo_root), site, repo_root)
add(leftout.PATH, t, d, b)
add("/data/changelog/", t, d, b, date=changelog)
entries = leftout.load_entries(repo_root)
t, d, b = leftout.left_out_page(entries, site, repo_root)
add(leftout.PATH, t, d, b, date=max((str(e.get("decided", "")) for e in entries), default=""))
# The visitor's own list: not indexed, and left out of the sitemap below.
t, d, b = saved.saved_page(records, site)
layout.write_page(out_dir, saved.PATH, layout.layout(
t, b, path=saved.PATH, description=d, maps=True, site=site, noindex=True))
pages += 1
docs.copy_licences(out_dir, repo_root)
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths), site)
feed.write_feed(out_dir, site, repo_root)
if site.base_url: # its links are absolute
with open(os.path.join(out_dir, "llms.txt"), "w", encoding="utf-8", newline="\n") as f:
f.write(seo.llms_txt(records, site, changelog))
seo.write_seo_files(out_dir, seo.all_paths(records, region_paths + ["/lists/"] + list_paths), site, dates)
print(f"pages written {pages}: {len(records)} trail pages, home, 404, places, lists, about")
return pages
+74 -9
View File
@@ -45,6 +45,34 @@ def _plural(n, word="trail"):
return f"{n} {word}{'' if n == 1 else 's'}"
def _with_gpx(n_gpx, total):
""""3 with a GPX here", or "all with a GPX here" when every one has; "" when none has."""
if not n_gpx:
return ""
return "all with a GPX here" if n_gpx == total else f"{n_gpx} with a GPX here"
def _miles(rec):
return words.fmt_int(rec["derived"]["length_mi"])
def _fit(options, limit=common.DESCRIPTION_LIMIT):
"""The first of options (fullest first) that fits; else the last, cut at a word."""
return common.cut_at_word(next((o for o in options if len(o) <= limit), options[-1]), limit)
def lists_here(recs, records):
"""The ready-made lists that hold some of these trails, as links with how many of them each
holds. A list that holds all of them (and there are several) says nothing about the place."""
ids = {r["id"] for r in recs}
parts = []
for lst, members in browse.shown(records):
k = sum(1 for m in members if m["id"] in ids)
if k and not (k == len(recs) > 1):
parts.append(f'<a href="{esc(browse.path(lst))}">{esc(lst.title)}</a> ({k})')
return parts
def regions_index_page(records, site):
"""(title, description, body) for /regions/: the Places hub."""
by_slug, across = collect_regions(records)
@@ -83,7 +111,9 @@ def regions_index_page(records, site):
</div></header>
<ul class="chips" aria-label="Jump to a part of the country">{"".join(jump)}</ul></div></div>
<div class="container section places">{blocks}</div>"""
return "Places", "Long trails by state and province, grouped into parts of the United States and Canada.", Markup(body)
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.")
return "Long Trails by State and Province: US and Canada", common.cut_at_word(description, common.DESCRIPTION_LIMIT), Markup(body)
def region_page(slug, records, site):
@@ -107,6 +137,9 @@ def region_page(slug, records, site):
siblings.append(f'<a href="{esc(facets.place_path(k))}">{esc(facets.place_name(k))}</a>')
nav = (f'<nav class="region-nav" aria-label="Elsewhere in {esc(group_name)}">Elsewhere in {esc(group_name)}: '
f'{" · ".join(siblings)}</nav>') if siblings else ""
held = lists_here(recs, records)
nav += (f'<nav class="region-nav" aria-label="Lists with trails in {esc(info["name"])}">'
f'Lists with trails in {esc(info["name"])}, and how many here: {" · ".join(held)}</nav>') if held else ""
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{crumbs}<li aria-current="page">{esc(info["name"])}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
@@ -118,11 +151,32 @@ def region_page(slug, records, site):
</div></div>
<div class="container section place">
{home.overview_map(recs, f"Map of the trails in {info['name']}")}
{home.results(recs)}
{home.results(recs, top=2)}
{nav}
</div>"""
title = info["name"]
desc = f"{_plural(len(recs))} in {info['name']}, {country}: length, time and where to get the GPX."
name = info["name"]
routes = sum(1 for r in recs if common.is_route(r))
mixed = 0 < routes < len(recs)
options = []
if mixed:
options.append(f"Long Trails in {name}: {_plural(len(recs) - routes, 'Trail')} and {_plural(routes, 'Route')}")
options.append(f"Long Trails in {name}: {len(recs)} Trails and Routes")
else:
options.append(f"Long Trails in {name}: {_plural(len(recs), 'Route' if routes else 'Trail')}")
options.append(f"Long Trails in {name}")
title = common.fit_title(options, site)
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
shortest, longest = by_length[0], by_length[-1]
what = _plural(len(recs), "trail") + (" and routes" if mixed else "")
if routes == len(recs):
what = _plural(len(recs), "route")
gpx = f" {_with_gpx(n_gpx, len(recs))[:1].upper()}{_with_gpx(n_gpx, len(recs))[1:]}." if n_gpx else ""
if len(recs) == 1:
first = f"{common.plain_name(longest)}, {_miles(longest)} miles, is the one long trail listed in {name}, {country}."
else:
first = (f"{what[:1].upper() + what[1:]} in {name}, {country}, from {common.plain_name(shortest)}, {_miles(shortest)} miles, "
f"to {common.plain_name(longest)}, {_miles(longest)} miles.")
desc = _fit([first + gpx, first, f"{what[:1].upper() + what[1:]} in {name}, {country}.{gpx}"])
return title, desc, Markup(body), home.has_overview_map(recs)
@@ -169,10 +223,13 @@ def routes_page(records, site, repo_root=None):
</div>
<div class="container section">
{home.overview_map(routes, "Map of the routes with a GPX here")}
{home.results(groups=groups, routes_list=True)}
{home.results(groups=groups, routes_list=True, top=2)}
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
</div>"""
return "Routes", f"{_plural(len(routes), 'route')} in the United States and Canada, by author, with their guides.", Markup(body), home.has_overview_map(routes)
description = (f"{_plural(len(routes), 'route')} in the United States and Canada by {len(by_author)} authors, "
f"with their guides{f' and {n_gpx} with a GPX here' if n_gpx else ''}.")
return (browse.by_key("routes").search_title(len(routes)), common.cut_at_word(description, common.DESCRIPTION_LIMIT),
Markup(body), home.has_overview_map(routes))
def list_page(lst, recs, total, site):
@@ -192,11 +249,16 @@ def list_page(lst, recs, total, site):
</div></div>
<div class="container section">
{home.overview_map(recs, f"Map of the trails in the list {lst.title}")}
{home.results(recs, default_sort=lst.sort)}
{home.results(recs, default_sort=lst.sort, top=2)}
<p class="finder__foot">{rule}</p>
<nav class="region-nav" aria-label="Other lists"><a href="/lists/">All lists</a> · <a href="/">Every trail</a></nav>
</div>"""
return lst.title, f"{lst.title}: {lst.blurb}", Markup(body), home.has_overview_map(recs)
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
stats = [f" {_plural(len(recs))}, from {common.plain_name(by_length[0])}, {_miles(by_length[0])} miles, "
f"to {common.plain_name(by_length[-1])}, {_miles(by_length[-1])} miles; {_with_gpx(n_gpx, len(recs)) or 'none with a GPX here'}.",
f" {_plural(len(recs))}, {_with_gpx(n_gpx, len(recs)) or 'none with a GPX here'}.", f" {_plural(len(recs))}."]
desc = _fit([lst.blurb + s for s in stats] + [lst.blurb])
return lst.search_title(len(recs)), desc, Markup(body), home.has_overview_map(recs)
def lists_index_page(records, site):
@@ -222,4 +284,7 @@ def lists_index_page(records, site):
<div class="container section"><ul class="shelves">{"".join(cards)}</ul>
<p class="finder__foot">A list is shown when it has at least {browse.MIN_SIZE} trails and no more than
{round(browse.MAX_SHARE * 100)}% of all of them. To combine conditions, use the filters on <a href="/">the home page</a>.</p></div>"""
return "Lists", "Ready-made lists of long trails: National Scenic Trails, routes, loops, the longest and more.", Markup(body)
shown = browse.shown(records)
desc = (f"{len(shown)} ready-made lists of the {len(records)} long trails, each picked out by rule from the records: "
f"by length, time, terrain, type and country.")
return "Long Hiking Trail Lists: Length, Terrain and Type", common.cut_at_word(desc, common.DESCRIPTION_LIMIT), Markup(body)
+193
View File
@@ -0,0 +1,193 @@
"""Links from one trail to others, worked out from the records alone.
Nothing here names a trail. Every link follows from a fact on the records:
similar close in length, with terrain or shape in common (similar_to)
related a trail whose own description names another, or two trails that
share a name (related_to)
lists which ready-made list a trail is in, and so which ones its page links to
Every trail is listed by at least MIN_INBOUND other trails' pages (similar_to), so
none is left without a way in. The results are worked out once for a set of
records and kept (a build asks for every trail in turn).
"""
import math
import re
from . import browse, facets, home
SIMILAR_EACH = 4 # each trail picks this many neighbours
SIMILAR_MAX = 6 # most shown on one page
MIN_INBOUND = 3 # every trail is listed on at least this many pages
RELATED_MAX = 6
LENGTH_SPAN = math.log(2.5) # trails more than 2.5 times apart in length are not alike
_CACHE = {}
def _once(key_records, name, build):
"""Keep build() for this very list of records (by identity)."""
slot = _CACHE.get(name)
if slot is None or slot[0] is not key_records:
slot = (key_records, build())
_CACHE[name] = slot
return slot[1]
# Similar trails -------------------------------------------------------------
def similarity(a, b):
"""How alike two trails are for a hiker choosing between them; below zero when they
are not alike. Length counts most (within a factor of 2.5), then the terrain they
share, then shape, kind and place."""
gap = abs(math.log(a["length_km"] / b["length_km"]))
if gap >= LENGTH_SPAN:
return -gap # not alike; the nearest in length still ranks first
ta, tb = set(facets.terrain(a)), set(facets.terrain(b))
shared = len(ta & tb)
score = 3.0 * (1 - gap / LENGTH_SPAN)
score += 3.0 * shared / max(1, len(ta | tb))
if shared == 0 and (ta or tb):
score -= 1.0
sa, sb = facets.shape(a), facets.shape(b)
if sa and sa == sb:
score += 1.0
if facets.kind(a) == facets.kind(b):
score += 0.75
ca, cb = set(facets.place_keys(a)), set(facets.place_keys(b))
if a["country"] == b["country"]:
score += 0.75
if ca & cb:
score += 0.5
return score
def _similar_graph(records):
"""id -> the trails its page lists as similar, best first.
Each trail picks SIMILAR_EACH of the trails most like it, leaning a little toward
trails that few others have picked yet, so that no trail is left unlinked. Then any
trail that fewer than MIN_INBOUND pages list is added to the pages of the trails
most like it that still have room (SIMILAR_MAX). A page lists only its own picks."""
by_id = {r["id"]: r for r in records}
score = {}
for r in records:
for o in records:
if r["id"] != o["id"]:
score[(r["id"], o["id"])] = similarity(r, o)
picks = {r["id"]: [] for r in records}
inbound = {r["id"]: 0 for r in records}
for r in sorted(records, key=lambda r: r["id"]):
rid = r["id"]
rows = []
for o in records:
oid = o["id"]
if oid == rid:
continue
lean = 0.6 if inbound[oid] < MIN_INBOUND else -0.2 * max(0, inbound[oid] - SIMILAR_EACH)
rows.append((score[(rid, oid)] + lean, oid))
rows.sort(key=lambda t: (-t[0], t[1]))
for _, oid in rows[:SIMILAR_EACH]:
picks[rid].append(oid)
inbound[oid] += 1
for oid in sorted(inbound, key=lambda i: (inbound[i], i)):
rows = sorted((-score[(rid, oid)], rid) for rid in picks
if rid != oid and oid not in picks[rid] and len(picks[rid]) < SIMILAR_MAX)
for _, rid in rows:
if inbound[oid] >= MIN_INBOUND:
break
picks[rid].append(oid)
inbound[oid] += 1
return {rid: sorted(others, key=lambda o: (-score[(rid, o)], o)) for rid, others in picks.items()}
def similar_to(rec, records):
"""Trails like this one, best match first: close in length, alike in terrain,
shape and place."""
graph = _once(records, "similar", lambda: _similar_graph(records))
by_id = {r["id"]: r for r in records}
return [by_id[i] for i in graph.get(rec["id"], [])]
def shared_terrain(a, b):
"""The terrain two trails have in common, in the first trail's order."""
tb = set(facets.terrain(b))
return [t for t in facets.terrain(a) if t in tb]
# Related trails -------------------------------------------------------------
_PAREN = re.compile(r"\s*\([^)]*\)")
def _plain(text):
return re.sub(r"[^\w]+", " ", text or "").strip().lower()
def _stems(rec):
"""The names a trail is called in running text: its name without any part in
brackets, and the common name. Two words or more, so a one-word name never matches."""
plain_name = _PAREN.sub("", rec["name"]).strip()
out = {plain_name, plain_name.split(",")[0].strip()}
if rec.get("common_name"):
out.add(rec["common_name"])
return {s for s in out if len(s.split()) >= 2}
def _prose(rec):
"""The record's own words about itself that its page shows near the top."""
h = rec.get("hike", {})
parts = [h.get("summary", ""), rec.get("designation", ""), h.get("caution", ""),
rec.get("route", {}).get("note", "")]
return " ".join(p for p in parts if p)
def _related_graph(records):
"""id -> {other id: reason}. "named": this trail's description names the other.
"names": the other's description names this trail. "name": they share a name."""
stems = {r["id"]: _stems(r) for r in records}
full = {r["id"]: _plain(r["name"] + " " + r.get("common_name", "")) for r in records}
out = {r["id"]: {} for r in records}
for r in records:
text = _prose(r)
for o in records:
if o["id"] == r["id"]:
continue
if any(re.search(r"(?<!\w)" + re.escape(s) + r"(?!\w)", text) for s in stems[o["id"]]):
out[r["id"]].setdefault(o["id"], "named")
out[o["id"]].setdefault(r["id"], "names")
# a shared name: one trail's name, as a whole phrase, is inside the other's full name
if any(f" {_plain(s)} " in f" {full[r['id']]} " for s in stems[o["id"]]) or \
any(f" {_plain(s)} " in f" {full[o['id']]} " for s in stems[r["id"]]):
out[r["id"]][o["id"]] = "name"
out[o["id"]][r["id"]] = "name"
return out
RELATED_ORDER = {"name": 0, "named": 1, "names": 2}
def related_to(rec, records):
"""[(trail, reason)] for the trails this one is tied to by what the records say,
shared names first, then the trails its description names, then trails whose
descriptions name it; the longest first within each."""
graph = _once(records, "related", lambda: _related_graph(records))
by_id = {r["id"]: r for r in records}
rows = [(by_id[i], why) for i, why in graph.get(rec["id"], {}).items()]
rows.sort(key=lambda t: (RELATED_ORDER[t[1]], -t[0]["length_km"], t[0]["id"]))
return rows[:RELATED_MAX]
# Lists ----------------------------------------------------------------------
def shown_lists(records):
"""{list key: List} for the lists that have a page of their own today."""
return _once(records, "lists", lambda: {lst.key: lst for lst, _ in browse.shown(records)})
def list_link(records, key):
"""(path, title) of the list, or None when it is not shown."""
if not records:
return None
lst = shown_lists(records).get(key)
return (browse.path(lst), lst.title) if lst else None
+466 -35
View File
@@ -1,49 +1,480 @@
"""Sitemap, robots.txt and the JSON-LD Dataset description."""
"""Sitemap, robots.txt, and the JSON-LD (schema.org) that describes each page.
Everything here is read from the records and from web/site.toml. No trail is
named in this file: a new record gets its markup from its own fields.
Types, and why (checked against schema.org and Google Search Central, 2026-11):
Trail page ItemPage, whose mainEntity is a Place that is also a
TouristAttraction. schema.org has no type for a trail
(schema.org/Trail is a 404), and Google has no trail or place
feature, so this markup is for search and assistants that read
entities, not for a rich result. A trail is a place a visitor
goes to, so Place is true of it; TouristAttraction is a
subtype of Place that "in principle any Thing can be". A route
is the same kind of place; the page says it is a route by its
author in additionalProperty. A route's author is free text in
the record (a person, two people, an association), so it is
never typed as Person or Organization.
Lists, places CollectionPage whose mainEntity is an ItemList of the trails.
Every page BreadcrumbList (a Google feature), read from the breadcrumb
the page shows, so the two cannot differ.
Home WebSite and Organization. A one-person open data project is
not a legal entity, but Organization is the type Google
documents for the publisher of a site; it carries only what
site.toml holds. No SearchAction: Google retired the sitelinks
search box.
/data/ Dataset (a Google feature), with its downloads.
dateModified is the newest date the record shows for itself (modified()),
never the build date, so a page's date moves only when its content does.
"""
import html
import os
import re
from html.parser import HTMLParser
from . import common
from . import common, docs, facets, hike, words
CC0 = "https://creativecommons.org/publicdomain/zero/1.0/"
# Media types of the files under /data/, which docs.BULK_FILES describes.
MEDIA_TYPES = {
"trails.csv": "text/csv",
"trails.json": "application/json",
"index.geojson": "application/geo+json",
"overview.geojson": "application/geo+json",
"all-gpx.zip": "application/zip",
"all-geojson.zip": "application/zip",
}
# The files under /data/ listed as the dataset's distribution: (name, media type).
DISTRIBUTION = (
("trails.csv", "text/csv"),
("trails.json", "application/json"),
("index.geojson", "application/geo+json"),
("overview.geojson", "application/geo+json"),
("all-gpx.zip", "application/zip"),
("all-geojson.zip", "application/zip"),
def distribution():
"""[(name, media type, what it holds)] for each bulk file, as the data page lists them."""
return [(name, MEDIA_TYPES[name], what) for name, what, _ in docs.BULK_FILES]
# What the dataset records for each trail (docs/schema.md), as variableMeasured.
VARIABLES = (
("length_km", "Published length of the trail", "KMT"),
("measured_km", "Length measured from the track, in kilometres", "KMT"),
("difference_percent", "Measured length against the published length, in per cent", "P1"),
("ascent_m", "Total climbing along the track, computed from an elevation model", "MTR"),
("days", "Usual time to walk the whole trail, as a source states it", "DAY"),
("regions", "States and provinces crossed", ""),
("terrain", "Main kinds of country", ""),
("shape", "End to end, loop or network", ""),
("source.licence", "Licence of the track, as its source states it", ""),
("verification.date", "Date the track was last checked", ""),
)
def dataset_jsonld(records, site):
"""One schema.org Dataset block for the home page and /data/."""
dist = []
for name, fmt in DISTRIBUTION:
url = site.canonical(f"/data/{name}") or f"/data/{name}"
dist.append({"@type": "DataDownload", "name": name, "encodingFormat": fmt, "contentUrl": url})
obj = {
"@context": "https://schema.org",
"@type": "Dataset",
"name": site.name,
"description": site.tagline,
"license": "https://creativecommons.org/publicdomain/zero/1.0/",
"distribution": dist,
"variableMeasured": ["length_km", "country", "regions", "source licence"],
}
if site.base_url:
obj["url"] = site.canonical("/")
# Dates -----------------------------------------------------------------------
def record_dates(rec):
"""Every date a record gives for its own checks and changes, as YYYY-MM-DD strings."""
found = [rec.get("verification", {}).get("date"), hike.table(rec).get("checked"),
rec.get("source", {}).get("source_checked")]
found += [e.get("date") for e in rec.get("history", []) if isinstance(e, dict)]
return [str(d) for d in found if d and re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(d))]
def modified(rec):
"""The newest of the record's check dates and its newest history entry, or ""."""
return max(record_dates(rec), default="")
def newest(recs):
"""The newest modified() among records: the date of a page that lists them."""
return max((modified(r) for r in recs), default="")
def earliest(recs):
"""The oldest date any record gives: when the first record was made."""
return min((d for r in recs for d in record_dates(r)), default="")
# JSON-LD ---------------------------------------------------------------------
def url_of(site, path):
"""Absolute URL of a site path, or the path itself when site.toml has no base_url."""
return site.canonical(path) or path
def country_names(records):
"""The countries the records cover, the United States first, as a phrase for a sentence:
"the United States and Canada"."""
codes = sorted({c for r in records for c in common.countries(r)}, key=lambda c: (c != "US", c))
return words.join_names(("the " if c == "US" else "") + words.COUNTRIES[c] for c in codes if c in words.COUNTRIES)
def breadcrumb_id(site, path):
return url_of(site, path) + "#breadcrumb"
def website_ref(site):
return {"@type": "WebSite", "@id": url_of(site, "/") + "#website", "name": site.name,
"url": url_of(site, "/")}
def _clean(obj):
"""Drop empty values, so a node holds only what the record has."""
if isinstance(obj, dict):
out = {k: _clean(v) for k, v in obj.items()}
return {k: v for k, v in out.items() if v not in ("", None, [], {})}
if isinstance(obj, list):
return [v for v in (_clean(x) for x in obj) if v not in ("", None, [], {})]
return obj
def sitemap_xml(paths, site):
"""sitemap.xml text for site paths; caller checks site.base_url is set."""
urls = "".join(
f" <url><loc>{html.escape(site.canonical(p), quote=True)}</loc></url>\n"
for p in paths)
def _pv(name, value, unit_code="", unit_text="", **extra):
node = {"@type": "PropertyValue", "name": name, "value": value}
if unit_code:
node["unitCode"] = unit_code
if unit_text:
node["unitText"] = unit_text
node.update(extra)
return node
class _Crumbs(HTMLParser):
"""The (text, href) items of the first <nav class="breadcrumb"> in a page body."""
def __init__(self):
super().__init__(convert_charrefs=True)
self.items = []
self._in_nav = False
self._done = False
self._cur = None
def handle_starttag(self, tag, attrs):
a = dict(attrs)
if tag == "nav" and not self._done and "breadcrumb" in (a.get("class") or "").split():
self._in_nav = True
elif self._in_nav and tag == "li":
self._cur = {"text": "", "href": ""}
elif self._in_nav and tag == "a" and self._cur is not None and not self._cur["href"]:
self._cur["href"] = a.get("href") or ""
def handle_endtag(self, tag):
if not self._in_nav:
return
if tag == "li" and self._cur is not None:
self._cur["text"] = " ".join(self._cur["text"].split())
self.items.append((self._cur["text"], self._cur["href"]))
self._cur = None
elif tag == "nav":
self._in_nav = False
self._done = True
def handle_data(self, data):
if self._cur is not None:
self._cur["text"] += data
def visible_breadcrumbs(body):
"""[(text, href)] of the breadcrumb a page body shows; the last item has no href."""
parser = _Crumbs()
parser.feed(str(body))
return parser.items
def breadcrumb_node(body, site, path, node_id=""):
"""A BreadcrumbList equal to the breadcrumb the body shows, ending at the page itself.
None when the page has none (the home page) or fewer than two items."""
crumbs = visible_breadcrumbs(body)
if not crumbs:
return None
items = []
for i, (text, href) in enumerate(crumbs, 1):
href = href or path # the current page: its own address
items.append({"@type": "ListItem", "position": i, "name": text,
"item": url_of(site, href) if href.startswith("/") else href})
if len(items) < 2:
return None
node = {"@type": "BreadcrumbList", "itemListElement": items}
if node_id:
node["@id"] = node_id
return node
def _extent(rec):
"""geo for a Place: a GeoShape box over the track, else over the two sketch points, else
the one point on file. Coordinates come from the record or its track, never made up."""
box = rec.get("derived", {}).get("bbox") or rec.get("derived", {}).get("map_bbox")
if not box:
pts = hike.sketch_points(rec)
if len(pts) == 1:
return {"@type": "GeoCoordinates", "longitude": pts[0][0], "latitude": pts[0][1]}
if pts:
box = hike.sketch_bbox(pts)
if not box:
return None
w, s, e, n = box
return {"@type": "GeoShape", "box": f"{s} {w} {n} {e}"}
def _same_as(rec):
urls = []
official = hike.table(rec).get("official_url")
if official:
urls.append(official)
relation = rec.get("osm", {}).get("relation")
if relation:
urls.append(f"https://www.openstreetmap.org/relation/{relation}")
for link in rec.get("link", []):
host = re.sub(r"^https?://([^/]+).*$", r"\1", link.get("url", "")).lower()
if host.endswith(("wikipedia.org", "wikidata.org")):
urls.append(link["url"])
return list(dict.fromkeys(urls))
def _contained_in(rec):
out = []
for key in facets.place_keys(rec):
if key == facets.ACROSS_CANADA:
out.append({"@type": "Country", "name": words.COUNTRIES["CA"]})
else:
out.append({"@type": "AdministrativeArea", "name": facets.place_name(key),
"containedInPlace": {"@type": "Country",
"name": words.COUNTRIES.get(key.split("-", 1)[0], "")}})
return out
def _properties(rec):
h = hike.table(rec)
mi = rec["derived"]["length_mi"]
props = [
_pv("Published length", mi, "SMI", "miles", description=rec.get("length_note", "")),
_pv("Published length", rec["length_km"], "KMT", "kilometres"),
]
days = h.get("days")
if isinstance(days, list) and len(days) == 2:
props.append(_pv("Usual time to walk it all", f"{days[0]} to {days[1]} days", "DAY", "days",
minValue=days[0], maxValue=days[1]))
elif isinstance(days, int):
props.append(_pv("Usual time to walk it all", days, "DAY", "days"))
if h.get("high_point_m"):
props.append(_pv("Highest point", h["high_point_m"], "MTR", "metres", description=h.get("high_point", "")))
elif h.get("high_point"):
props.append(_pv("Highest point", h["high_point"]))
shape = facets.shape(rec)
if shape:
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)
if common.is_route(rec):
route = rec.get("route", {})
props.append(_pv("Route author", route["creator"]) if route.get("creator") else None)
props.append(_pv("First published", route["year"]) if route.get("year") else None)
elif rec.get("designation"):
props.append(_pv("Designation", rec["designation"]))
return [p for p in props if p]
def _downloads(rec, site):
"""The main track files, as DataDownload nodes with the track's own terms."""
src = rec.get("source", {})
licence = words.LICENCE_URLS.get(src.get("licence", ""), "")
types = {"GPX": "application/gpx+xml", "GeoJSON": "application/geo+json"}
out = []
for d in rec.get("derived", {}).get("downloads", []):
if d.get("role") != "main":
continue
node = {"@type": "DataDownload", "name": f"{rec['name']}: track as {d['format']}",
"encodingFormat": types.get(d["format"], ""),
"contentUrl": url_of(site, f"/trails/{rec['id']}/{d['file']}"),
"isAccessibleForFree": True, "creditText": src.get("attribution", "")}
if licence:
node["license"] = licence
else: # a licence with no page of its own: the trail page states the terms
node["usageInfo"] = url_of(site, f"/trails/{rec['id']}/#download")
out.append(node)
return out
def _guides(rec):
"""A route's guides (and any other trail's own guide) as CreativeWork nodes."""
return [{"@type": "CreativeWork", "name": g.get("title", ""), "url": g.get("url", ""),
"isAccessibleForFree": g.get("access") == "free" if g.get("access") else None}
for g in rec.get("guide", [])]
def place_node(rec, site):
"""The trail or route as a Place and TouristAttraction, from the record alone."""
page = url_of(site, f"/trails/{rec['id']}/")
names = [n for n in (rec.get("common_name"), rec.get("short_name")) if n and n != rec["name"]]
node = {
"@type": ["Place", "TouristAttraction"],
"@id": page + "#trail",
"name": rec["name"],
"alternateName": list(dict.fromkeys(names)),
"description": hike.summary(rec),
"url": page,
"sameAs": _same_as(rec),
"containedInPlace": _contained_in(rec),
"geo": _extent(rec),
"additionalProperty": _properties(rec),
"subjectOf": _downloads(rec, site) + _guides(rec),
}
return _clean(node)
def page_node(kind, path, site, *, name, description="", date="", main=None, breadcrumb_id=""):
node = {"@type": kind, "@id": url_of(site, path) + "#webpage", "url": url_of(site, path),
"name": name, "description": description, "inLanguage": "en", "dateModified": date,
"isPartOf": website_ref(site) if path != "/" else None,
"breadcrumb": {"@id": breadcrumb_id} if breadcrumb_id else None,
"mainEntity": main}
return _clean(node)
def trail_jsonld(rec, site, *, title, description):
"""The nodes for one trail page: its ItemPage and its Place. layout.layout adds the breadcrumb."""
path = f"/trails/{rec['id']}/"
place = place_node(rec, site)
return [page_node("ItemPage", path, site, name=title, description=description, date=modified(rec),
main={"@id": place["@id"]}, breadcrumb_id=breadcrumb_id(site, path)), place]
def collection_jsonld(path, site, *, title, description, recs, date=""):
"""CollectionPage and its ItemList for a list or a place: the trails the page lists."""
items = [{"@type": "ListItem", "position": i, "name": r["name"], "url": url_of(site, common.trail_path(r))}
for i, r in enumerate(recs, 1)]
listing = {"@type": "ItemList", "numberOfItems": len(items), "itemListElement": items}
return [page_node("CollectionPage", path, site, name=title, description=description,
date=date or newest(recs), main=listing,
breadcrumb_id=breadcrumb_id(site, path))]
def organization_node(site):
"""The publisher: name, address, logo, and the repository and contact site.toml holds."""
node = {"@type": "Organization", "@id": url_of(site, "/") + "#organization", "name": site.name,
"url": url_of(site, "/"), "description": site.tagline,
"logo": url_of(site, "/assets/apple-touch-icon.png"),
"sameAs": [site.repo_url] if site.repo_url else []}
contact = site.contact_url
if contact.startswith("mailto:"):
node["email"] = contact[len("mailto:"):]
elif contact:
node["contactPoint"] = {"@type": "ContactPoint", "url": contact, "contactType": "customer support"}
return _clean(node)
def home_jsonld(site):
"""WebSite and Organization for the home page."""
org = organization_node(site)
web = {"@type": "WebSite", "@id": url_of(site, "/") + "#website", "name": site.name,
"url": url_of(site, "/"), "description": site.tagline, "inLanguage": "en",
"publisher": {"@id": org["@id"]}}
return [web, org]
def dataset_jsonld(records, site, *, version=""):
"""The Dataset for /data/: what it holds, who made it, its terms, and every download."""
dist = []
for name, fmt, what in distribution():
node = {"@type": "DataDownload", "name": name, "description": what, "encodingFormat": fmt,
"contentUrl": url_of(site, f"/data/{name}")}
dist.append(node)
codes = sorted({c for r in records for c in common.countries(r)}, key=lambda c: (c != "US", c))
countries = [words.COUNTRIES[c] for c in codes if c in words.COUNTRIES]
n_tracks = sum(1 for r in records if common.has_line(r))
boxes = [r["derived"]["bbox"] for r in records if r.get("derived", {}).get("bbox")]
spatial = {"@type": "Place", "name": words.join_names(countries)}
if boxes:
s, w = min(b[1] for b in boxes), min(b[0] for b in boxes)
n, e = max(b[3] for b in boxes), max(b[2] for b in boxes)
spatial["geo"] = {"@type": "GeoShape", "box": f"{s} {w} {n} {e}"}
first, last = earliest(records), newest(records)
lead = site.tagline.split(",")[0]
publisher = organization_node(site)
obj = {
"@type": "Dataset",
"@id": url_of(site, "/data/") + "#dataset",
"name": f"{site.name}: {lead}",
"description": (
f"{len(records)} records of long-distance hiking trails and routes in {country_names(records)}. "
f"Each record gives the trail's length, the places it crosses, where to read more about it and a "
f"source for every fact; {n_tracks} also have a track, as GPX and GeoJSON. The records and the "
f"compiled index are public domain (CC0 1.0). Each track keeps the licence of its source, named "
f"in its record and on its trail page."),
"url": url_of(site, "/data/"),
"license": CC0,
"isAccessibleForFree": True,
"keywords": ["long-distance hiking trails", "hiking", "backpacking", "thru-hiking", "GPX", "GeoJSON",
"trail length", "open data"] + countries,
"creator": publisher,
"publisher": publisher,
"sameAs": site.repo_url,
"spatialCoverage": spatial,
"temporalCoverage": f"{first}/{last}" if first and last else "",
"dateModified": last,
"datePublished": first,
"version": version,
"measurementTechnique": (
"Each track's length is measured along the track and compared with the length the trail's "
"holder publishes. Climbing is computed from the track and an open elevation model."),
"variableMeasured": [{"@type": "PropertyValue", "name": name, "description": what, "unitCode": unit}
for name, what, unit in VARIABLES],
"distribution": dist,
}
return _clean(obj)
# llms.txt ---------------------------------------------------------------------
def llms_txt(records, site, version=""):
"""/llms.txt in the llmstxt.org shape: what the site is, its licence, and where the
bulk files and the per-trail files are. Google says it does not use the file for
Search, so this is for assistants and tools that fetch the data. It carries what
/data/ says in tables, as plain links, and lists no trail (trails.json does)."""
n_tracks = sum(1 for r in records if common.has_line(r))
u = lambda path: url_of(site, path) # noqa: E731
lines = [
f"# {site.name}", "",
f"> {site.tagline}. {len(records)} records, {n_tracks} with a track. Every fact in a record "
f"names the page it was read on.", "",
"The records and the compiled index are public domain (CC0 1.0). Each track keeps the licence "
"of its source, named in its record, on its trail page and in its release.txt. Trail logos "
"belong to their holders. The data is not for navigation.", "",
"## Bulk data", "",
]
for name, kind, what in distribution():
lines.append(f"- [{name}]({u('/data/' + name)}): {what} ({kind})")
lines += ["", "## One trail", "",
f"- A trail's page is {u('/trails/')}<id>/ . Its files sit beside it, named by the same id.",
f"- {u('/trails/')}<id>/trail.toml: the record itself, with its sources and licence.",
f"- {u('/trails/')}<id>/<id>.gpx and <id>.geojson: the main track, where the record includes one.",
f"- {u('/trails/')}<id>/release.txt: the source, licence and date of the track.",
"- The ids are the `id` column of trails.csv.", "",
"## About the data", "",
f"- [Data and downloads]({u('/data/')}): every file, and every licence.",
f"- [Record schema]({u('/data/schema/')}): what each field of a record means.",
f"- [Sources and their terms]({u('/sources/')}): who publishes each track, and on what terms.",
f"- [Considered and left out]({u('/left-out/')}): trails looked at and not included, with the reason.",
f"- [Changelog]({u('/data/changelog/')}) and its [Atom feed]({u('/feed.xml')})"
+ (f"; the latest release is dated {version}" if version else "") + ".",
f"- [Source repository and issue tracker]({site.repo_url})" if site.repo_url else None]
return "\n".join(x for x in lines if x is not None) + "\n"
# Sitemap and robots -----------------------------------------------------------
def sitemap_xml(paths, site, lastmod=None):
"""sitemap.xml text for site paths; caller checks site.base_url is set.
lastmod: {path: YYYY-MM-DD}. A path with no date gets no <lastmod>: a date
that is not the page's own is worse than none."""
lastmod = lastmod or {}
rows = []
for p in paths:
stamp = f"<lastmod>{lastmod[p]}</lastmod>" if lastmod.get(p) else ""
rows.append(f" <url><loc>{html.escape(site.canonical(p), quote=True)}</loc>{stamp}</url>\n")
return ('<?xml version="1.0" encoding="UTF-8"?>\n'
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
f"{urls}</urlset>\n")
f"{''.join(rows)}</urlset>\n")
def robots_txt(site):
@@ -53,14 +484,14 @@ def robots_txt(site):
return "\n".join(lines).rstrip() + "\n"
def write_seo_files(out_dir, paths, site):
def write_seo_files(out_dir, paths, site, lastmod=None):
"""Write robots.txt always and sitemap.xml only with a base_url."""
with open(os.path.join(out_dir, "robots.txt"), "w", encoding="utf-8", newline="\n") as f:
f.write(robots_txt(site))
sitemap = os.path.join(out_dir, "sitemap.xml")
if site.base_url:
with open(sitemap, "w", encoding="utf-8", newline="\n") as f:
f.write(sitemap_xml(paths, site))
f.write(sitemap_xml(paths, site, lastmod))
elif os.path.isfile(sitemap):
os.remove(sitemap) # a stale sitemap with wrong URLs is worse than none
+6 -3
View File
@@ -1,4 +1,4 @@
"""Site-wide settings from web/site.toml (name, tagline, base_url, repo_url, repo_branch, contact_url, name_lang)."""
"""Site-wide settings from web/site.toml (name, tagline, home_title, base_url, repo_url, repo_branch, contact_url, name_lang)."""
import functools
import os
import tomllib
@@ -12,11 +12,13 @@ class Site:
"""The settings every page needs. Build one with load()."""
def __init__(self, name, tagline, base_url="", repo_url="", repo_branch="main",
contact_url="", name_lang=None):
contact_url="", name_lang=None, home_title=""):
if not name:
raise ValueError("site.toml: name must not be empty")
self.name = name
self.tagline = tagline
# The home page's own title, before the name is added (about 50 characters).
self.home_title = home_title.strip()
self.base_url = base_url.rstrip("/")
self.repo_url = repo_url.rstrip("/")
self.repo_branch = (repo_branch or "main").strip() or "main"
@@ -103,7 +105,8 @@ def from_file(path):
return Site(name=data.get("name", ""), tagline=data.get("tagline", ""),
base_url=data.get("base_url", ""), repo_url=data.get("repo_url", ""),
repo_branch=data.get("repo_branch", "main"),
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}))
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}),
home_title=data.get("home_title", ""))
@functools.cache
+166 -27
View File
@@ -8,7 +8,7 @@ import os
import re
import urllib.parse
from . import common, elevation, facets, hike, words
from . import browse, common, elevation, facets, hike, related, words
from .layout import OUTDOOR_STYLE
from .markup import Markup, esc
@@ -165,6 +165,10 @@ def page_head(rec):
has_plate = bool(common.shield_url(rec))
abbr = rec.get("short_name", "")
abbr_html = f' <span class="titleblock__abbr">{esc(abbr)}</span>' if abbr else ""
# The name hikers use leads the page; the recorded name stays, just under it.
common_name = rec.get("common_name", "")
heading = esc(common_name) if common_name else common.name(rec)
full_name = f'<p class="titleblock__sub">Full name: {common.name(rec)}</p>' if common_name else ""
plate = common.plate(rec, size="lg", link=True, eager=True) if has_plate else ""
summary = hike.summary(rec)
lede = common.rich(summary) if summary else fallback_lede(rec)
@@ -193,8 +197,8 @@ def page_head(rec):
{plate}
<div class="titleblock__text">
{kicker}
<h1>{common.name(rec)}{abbr_html}</h1>
{f'<p class="titleblock__sub">{common.rich(lead)}</p>' if lead else ""}
<h1>{heading}{abbr_html}</h1>
{full_name}{f'<p class="titleblock__sub">{common.rich(lead)}</p>' if lead else ""}
{define}
</div>
</header>
@@ -205,6 +209,14 @@ def page_head(rec):
</div>"""
def shape_label(rec, records):
""""Loop" (linked to the loops list when it is shown), "End to end" or "Network"."""
label = facets.SHAPES[facets.shape(rec)]
if facets.shape(rec) == "loop":
return list_anchor(records, "loops", label) or esc(label)
return esc(label)
def glance_row(label, value, note="", wide=False):
note_html = f"<small>{note if isinstance(note, Markup) else esc(note)}</small>" if note else ""
value_html = value if isinstance(value, Markup) else esc(value)
@@ -212,16 +224,52 @@ def glance_row(label, value, note="", wide=False):
f'<dd>{value_html}{note_html}</dd></div>')
def glance(rec):
"""The hiker's facts at a glance, under the attribute names every page uses."""
def list_anchor(records, key, text):
"""text linked to the list's page when that list is shown today (browse.is_shown); else None."""
link = related.list_link(records, key) if records else None
return Markup(f'<a href="{esc(link[0])}">{esc(text)}</a>') if link else None
# The time lists, by the band a trail falls in (facets.time_band).
TIME_LISTS = {"week": "a-week-or-less", "two-weeks": "one-to-two-weeks"}
def length_note(rec, records):
"""A link under the length to the list its length puts it in: the shortest or the longest."""
for key, text in (("under-100-miles", f"More trails under {browse.SHORT_MI} miles"),
("longest", f"More trails of {browse.LONG_MI:,} miles or more")):
if related.list_link(records, key) and browse.by_key(key).test(rec):
return list_anchor(records, key, text)
return ""
def time_note(rec, records):
"""The estimate's note, then a link to the list of trails that take as long."""
note = facets.estimate_note(rec)
key = TIME_LISTS.get(facets.time_band(rec))
if not key or not related.list_link(records, key):
return note
text = f"More trails of {browse.by_key(key).title.lower()}"
return Markup(f"{note} {list_anchor(records, key, text)}" if note else str(list_anchor(records, key, text)))
def glance(rec, records=None):
"""The hiker's facts at a glance, under the attribute names every page uses.
records: every trail, so that terrain, shape, time and length link to the
lists they put the trail in (left out when None)."""
h = hike.table(rec)
rows = [glance_row(facets.LENGTH, words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]))]
rows.append(glance_row(facets.TIME, facets.time_text(rec), facets.estimate_note(rec)))
rows = [glance_row(facets.LENGTH, words.length(rec["length_km"], "stack", rec["derived"]["length_mi"]),
length_note(rec, records))]
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))
if facets.walking(rec):
rows.append(glance_row(facets.WALKING, facets.WALKING_VALUES[facets.walking(rec)]))
walking = facets.WALKING_VALUES[facets.walking(rec)]
if facets.walking(rec) in facets.CROSS_COUNTRY:
walking = list_anchor(records, "off-trail", walking) or walking
rows.append(glance_row(facets.WALKING, walking))
elev = elevation.get(rec)
if h.get("high_point") or h.get("high_point_m"):
# A named, sourced high point is better than a computed number.
@@ -250,14 +298,16 @@ def glance(rec):
if isinstance(text, tuple):
text = Markup(f'{esc(text[0])}<span class="glance__to"> to </span>{esc(text[1])}')
if facets.shape(rec):
text = Markup(f'<strong>{esc(facets.SHAPES[facets.shape(rec)])}.</strong> {esc(text) if not isinstance(text, Markup) else text}')
text = Markup(f'<strong>{shape_label(rec, records)}.</strong> {esc(text) if not isinstance(text, Markup) else text}')
label = facets.SHAPE
rows.append(glance_row(label, text, wide=True))
elif facets.shape(rec):
rows.append(glance_row(facets.SHAPE, facets.SHAPES[facets.shape(rec)]))
rows.append(glance_row(facets.SHAPE, shape_label(rec, records)))
terrain = facets.terrain(rec)
if terrain:
rows.append(glance_row(facets.TERRAIN, ", ".join(words.TERRAIN[t] for t in terrain), wide=True))
names = Markup(", ".join(str(list_anchor(records, f"terrain-{t}", words.TERRAIN[t]) or esc(words.TERRAIN[t]))
for t in terrain))
rows.append(glance_row(facets.TERRAIN, names, wide=True))
if h.get("permit"):
rows.append(glance_row("Permits", common.sentence(h["permit"]), wide=True))
country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec))
@@ -786,6 +836,8 @@ def record_block(rec):
where = Markup(f'{codes}{names_html}, {esc(country)}')
rows = [
fact("Kind", words.label(words.KINDS, k), words.meaning(words.KINDS, k)),
fact("Common name", rec["common_name"], "The name hikers use, where it differs from the name above.")
if rec.get("common_name") else "",
fact("Designation", rec.get("designation", "")),
fact("Tier", words.label(words.TIERS, tier), words.meaning(words.TIERS, tier)),
fact("Listing", words.label(words.WAVES, wave), listing_note(rec)),
@@ -1190,17 +1242,87 @@ def raw_record(rec):
# The page -------------------------------------------------------------------
def gpx_offered(rec):
"""True when the page offers a GPX download (the build lists its files in derived.downloads)."""
downloads = rec["derived"].get("downloads")
if downloads is None:
return common.has_line(rec)
return any(d.get("format") == "GPX" for d in downloads)
def page_title(rec, site):
"""The page's own title, before the site name is added: the name hikers use, the
abbreviation where there is one, the length in miles, and what the page offers.
Only what is true of the page: GPX only where it has a download, a map only
where it has a track.
The whole title, site name included, stays within common.TITLE_LIMIT. Pieces go in
this order until it fits: the kilometres, the author of a route, the word
"map", the abbreviation, then "GPX". A route says it is a route.
"""
name = common.plain_name(rec)
abbr = rec.get("short_name", "")
named = f"{name} ({abbr})" if abbr and abbr.lower() != name.lower() else name
mi = words.fmt_int(rec["derived"]["length_mi"])
km = words.fmt_km(rec["length_km"])
gpx = gpx_offered(rec)
who = facets.author(rec)
route = common.is_route(rec)
def text(head, with_km, with_who, offer):
if route:
tail = f"{mi}-mile route" + (f" by {who}" if with_who and who else "")
else:
tail = f"{mi} miles" + (f" ({km} km)" if with_km else "")
return f"{head}: {tail}" + {2: ", map and GPX", 1: ", GPX", 0: ""}[offer if gpx else 0]
steps = ((named, True, True, 2), (named, False, False, 2), (named, False, False, 1),
(name, False, False, 1), (name, False, False, 0))
options = []
for step in steps:
option = text(*step)
if option not in options:
options.append(option)
return common.fit_title(options, site)
def places_short(rec):
"""Where it is, for a description: "in Oregon", "in Utah and Wyoming",
"across 14 states", "across Canada"."""
codes = rec.get("regions", [])
if words.ALL_CANADA in codes:
return "across Canada"
countries = [words.COUNTRIES.get(c, c) for c in common.countries(rec)] or \
[words.COUNTRIES.get(rec["country"], rec["country"])]
if not codes:
return f"in {words.join_names(countries)}"
if len(codes) > 3:
unit = {"United States": "states", "Canada": "provinces and territories"}.get(
words.join_names(countries), "states and provinces")
return f"across {len(codes)} {unit}"
return f"in {words.join_names(words.region_name(c) for c in codes)}"
def description(rec):
one = hike.one_line(rec)
if one:
text = one
else:
km = words.fmt_km(rec["length_km"])
mi = words.fmt_int(rec["derived"]["length_mi"])
text = f"{rec['name']}: a {kind_word(rec)} of {mi} mi ({km} km) {place_text(rec)}."
text += (" Download its GPX here." if common.has_line(rec)
else " Where to get its GPX.")
return text if len(text) <= 300 else text[:297].rsplit(" ", 1)[0] + "…"
"""The meta description, from the record's own fields and at most DESCRIPTION_LIMIT
characters: what it is, how long, where, the usual time where a source states one,
then the first sentence of the summary (or the designation where there is none)."""
mi = words.fmt_int(rec["derived"]["length_mi"])
km = words.fmt_km(rec["length_km"])
text = f"A {kind_word(rec)} of {mi} miles ({km} km) {places_short(rec)}"
days = hike.days(rec)
if days:
text += f", usually {days}"
text += "."
tail = hike.one_line(rec)
if not tail and rec.get("designation"):
tail = rec["designation"].strip()
tail = tail[:1].upper() + tail[1:]
if not tail.endswith("."):
tail += "."
if tail:
text += " " + tail
return common.cut_at_word(re.sub(r"\s+", " ", text.replace("`", "")), common.DESCRIPTION_LIMIT)
# Ways onward ------------------------------------------------------------------
@@ -1208,11 +1330,12 @@ def description(rec):
ONWARD_MAX = 6
def _onward_list(title, recs, more_href, more_text, heading_id):
def _onward_list(title, recs, more_href, more_text, heading_id, meta=None):
"""One list of ways onward: each trail's name and length, then meta(r) (HTML) where given."""
items = "".join(
f'<li><a href="{esc(common.trail_path(r))}">{common.name(r)}</a>'
f'<span class="onward__len">{words.length(r["length_km"], "short", r["derived"]["length_mi"])}'
f'{" · Route" if common.is_route(r) else ""}</span></li>'
f'{" · Route" if common.is_route(r) else ""}{meta(r) if meta else ""}</span></li>'
for r in recs[:ONWARD_MAX])
more = (f'<p class="onward__more"><a href="{esc(more_href)}">{esc(more_text)}</a></p>'
if more_href else "")
@@ -1220,13 +1343,23 @@ def _onward_list(title, recs, more_href, more_text, heading_id):
f'<h3 id="{heading_id}">{esc(title)}</h3><ul class="onward__list">{items}</ul>{more}</section>')
RELATED_WHY = {"name": "same name", "named": "named here", "names": "mentions this"}
def onward(rec, records):
"""Ways onward at the foot of the page: other trails in the same state or province
(up to three of them), and for a route, other routes by the same author."""
"""Ways onward at the foot of the page, all worked out from the records (olt/related.py):
trails tied to this one by name or by what the descriptions say; other trails in the
same state or province (up to three of them); trails like this one in length, terrain
and shape; and for a route, other routes by the same author."""
if not records:
return ""
others = [r for r in records if r["id"] != rec["id"]]
parts = []
tied = related.related_to(rec, records)
if tied:
why = {r["id"]: w for r, w in tied}
parts.append(_onward_list("Related trails", [r for r, _ in tied], "", "", "onward-related",
meta=lambda r: f" · {esc(RELATED_WHY[why[r['id']]])}"))
for i, key in enumerate(k for k in facets.place_keys(rec) if k != facets.ACROSS_CANADA):
if i >= 3:
break
@@ -1237,6 +1370,12 @@ def onward(rec, records):
more = (facets.place_path(key), f"All {len(here) + 1} trails in {name}") if len(here) > ONWARD_MAX else \
(facets.place_path(key), f"{name} on the map")
parts.append(_onward_list(f"More in {name}", here, more[0], more[1], f"onward-{key.lower()}"))
like = related.similar_to(rec, records)
if like:
def alike(r):
shared = related.shared_terrain(rec, r)
return f" · {esc(', '.join(words.TERRAIN[t].lower() for t in shared))}" if shared else ""
parts.append(_onward_list("Similar in length and terrain", like, "", "", "onward-similar", meta=alike))
who = facets.author(rec)
if who:
same = sorted((r for r in others if facets.author(r) == who), key=lambda r: -r["length_km"])
@@ -1260,7 +1399,7 @@ def render(rec, site, records=None):
profile = elevation_figure(rec)
body = f"""{page_head(rec)}
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
{glance(rec)}
{glance(rec, records)}
{map_figure(rec) if has_track else sketch_figure(rec) if sketch else empty_frame(rec)}
{profile}
{aside_html}
@@ -1271,7 +1410,7 @@ def render(rec, site, records=None):
{about_data(rec, site)}
{history_section(rec)}
</div>"""
return rec["name"], description(rec), body, has_map
return page_title(rec, site), description(rec), body, has_map
def release_path(repo_root, rec):