"""One page per record: /trails//. The main sections say what the record says, in plain words. Every field of the record, with its exact value, is in the table at the end of the page (raw_record); the main flow carries no coded values. """ import os import re import urllib.parse from . import browse, common, elevation, facets, hike, regions, related, seo, sketch, words from .layout import OUTDOOR_STYLE from .markup import Markup, esc EXTRACT_SOURCES = {"osm": "OpenStreetMap", "usfs": "USDA Forest Service", "nps": "National Park Service"} GAUGE_MIN, GAUGE_MAX, GAUGE_LIMIT = -40.0, 40.0, common.LENGTH_LIMIT # Download formats in the order a hiker most likely wants them: GPX for devices first. FORMAT_ORDER = ("GPX", "GeoJSON") # Small building blocks ------------------------------------------------------ def code(value): return Markup(f'{esc(value)}') def fact(label, value, note=""): """One label/value row of a facts list. note: smaller text under the value. Plain-string values and notes are record text: escaped, with `backticked` spans set as code. """ value_html = value if isinstance(value, Markup) else common.rich(value) note_html = f"{note if isinstance(note, Markup) else common.rich(note)}" if note else "" return Markup(f"
{esc(label)}
{value_html}{note_html}
") def facts(*rows): rows = [r for r in rows if r] return Markup('
' + "".join(rows) + "
") if rows else Markup("") def ext_link(url, text=None): return Markup(f'{esc(text or url)}') def host(url): netloc = urllib.parse.urlsplit(url).netloc return netloc[4:] if netloc.startswith("www.") else netloc def yes_no(value): return "Yes" if value else "No" def block(id_, title, content, extra=""): """A section of the main column. Its heading carries the id; the section is not a landmark (no aria-labelledby): a page has many of them.""" return Markup(f'
' f'

{esc(title)}{extra}

{content}
') def record_text(text, cls=""): return Markup(f'

{common.rich(text)}

') def restates_no_line(value): """True for record values that only say there is no track ("none (no line included)").""" text = str(value or "").strip().lower() return text.startswith(("none (no line", "no line included", "no line to measure", "none (no track", "no track included", "no track to measure")) def region_names(rec): """The states and provinces for the glance, each linked to its place page; codes when there are many.""" keys = facets.place_keys(rec) parts = [] for key in keys: name = facets.place_name(key) text = esc(name) if len(keys) <= 3 or key == facets.ACROSS_CANADA else \ Markup(f'{esc(key.split("-", 1)[1])}') parts.append(f'{text}') return Markup((", " if len(keys) <= 3 else " ").join(parts)) _ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)") def org_name(text): """The organisation or person a record names, without the record's own remarks: "Green Mountain Club (publishes the trail); its ArcGIS ..." -> "Green Mountain Club".""" name = _ORG_CUT.split(text or "", maxsplit=1)[0].strip() return name[:1].upper() + name[1:] # Page head ------------------------------------------------------------------ def kind_word(rec): return "route" if common.is_route(rec) else "trail" def place_text(rec): """Where it is, for a sentence: "in Oregon, United States", "across 14 states of the United States", "across 9 states and provinces of the United States and Canada".""" codes = rec.get("regions", []) countries = [words.COUNTRIES.get(c, c) for c in common.countries(rec)] or \ [words.COUNTRIES.get(rec["country"], rec["country"])] country = words.join_names(countries) if words.ALL_CANADA in codes or not codes: return f"across {country}" if words.ALL_CANADA in codes else f"in {country}" if len(codes) > 3: unit = {"United States": "states", "Canada": "provinces and territories"}.get(country, "states and provinces") the = words.join_names(("the " + c) if c == "United States" else c for c in countries) return f"across {len(codes)} {unit} of {the}" return f"in {words.join_names(words.region_name(c) for c in codes)}, {country}" def fallback_lede(rec): """A one-sentence description built from the record, for a record without a [hike] summary.""" length_html = words.length(rec["length_km"], "inline", rec["derived"]["length_mi"]) return Markup(f"A {kind_word(rec)} of {length_html} {esc(place_text(rec))}.") def lead_line(rec): """Who made or designated it: "Route by Steve Roper, 1970", or the trail's designation.""" if common.is_route(rec): return facets.route_by(rec) return rec.get("designation", "") def credit_html(rec, credit, author_links=None): """A route's credit as HTML, each author's name in it a link to their page (olt/authors.py link_map).""" text = str(esc(credit)) for name, href in (author_links or {}).get(facets.author(rec), []): n = str(esc(name)) if n in text: text = text.replace(n, f'{n}', 1) return Markup(text) def lead_html(rec, lead, author_links=None): """The lead line as HTML; on a route, the author's name in it links to the author's page (author_links: {credit: [(name, path)]} from olt/authors.py).""" links = (author_links or {}).get(facets.author(rec)) if common.is_route(rec) else None if not links: return common.rich(lead) text = str(esc(lead)) for name, href in links: n = str(esc(name)) if n in text: text = text.replace(n, f'{n}', 1) return Markup(text) def route_definition(): """What a route is, one tap away from the Kind line of a route's page (no script needed).""" return Markup(f'
What is a route?' f'

{esc(facets.ROUTE_DEFINITION)} Every route.

') # What a guide's address is, by the record's `link_is`, as the link's words. LINK_IS_TEXT = { "publisher": "The publisher's page for this book", "author": "The author's page for this guide", "library": "Library record (out of print)", "seller": "Bookseller's page", } def _same_page(a, b): """True when two addresses are the same page (scheme, www and a trailing slash aside).""" def key(u): parts = urllib.parse.urlsplit(str(u or "").strip()) return (parts.netloc.lower().removeprefix("www."), parts.path.rstrip("/"), parts.query) return bool(a) and bool(b) and key(a) == key(b) def guide_link_text(g): """What the guide's link says it is; today's words when the record does not say.""" return LINK_IS_TEXT.get(g.get("link_is")) or f"Guide page on {host(g.get('url', ''))}" def sold_guide_page(rec, url): """The purchase guide whose address `url` is, or whose host it shares when that guide's page is the publisher's or a bookseller's: a page that sells the guide is not the route's own page. None when `url` is the route's own.""" for g in rec.get("guide", []): if g.get("access") != "purchase" or not g.get("url"): continue if _same_page(g["url"], url) or (host(g["url"]) == host(url) and g.get("link_is") in ("publisher", "seller")): return g return None GUIDE_LABELS = set(LINK_IS_TEXT.values()) | {"The guide's page", "The route's guide"} def _see_clause(rec): """", so see the official site", or ", so see the guide" when the page on offer is a guide's.""" link = official_link(rec) if not link: return "" return ", so see the guide" if link[1] in GUIDE_LABELS else ", so see the official site" def official_link(rec): """(url, label) of the trail's own page: the [hike] official site, else the publisher's page for the trail, else a route's free guide; None when the record has none. An "official site" that is the page selling a guide to the route is labelled as that page.""" url = hike.official_url(rec) if url: sold = sold_guide_page(rec, url) if sold: return url, LINK_IS_TEXT.get(sold.get("link_is")) or "The guide's page" return url, "Official site" src = rec.get("source", {}) if src.get("publisher_url"): who = org_name(src.get("publisher", "")) return src["publisher_url"], (f"{who} website" if who else "The trail's website") if common.is_route(rec): for g in rec.get("guide", []): if g.get("url"): return g["url"], "The route's guide" return None # The kinds of country, as an adjective before "country": "forest and alpine country". TERRAIN_ADJECTIVE = {"alpine": "alpine", "forest": "forest", "desert": "desert", "coast": "coastal", "prairie": "prairie", "canyon": "canyon", "tundra": "tundra", "lakes": "lake", "farmland": "farmland"} # What the walking is (docs/schema.md `travel`). WALKING_ALONE = { "trail": "It is on built or maintained trail all or nearly all the way.", "trail-and-road": "It is on trail, with long stretches on roads.", "some-cross-country": "It is mostly on trail or road, with stretches that have no trail.", "mostly-cross-country": "It has no trail for most of the way.", } # An author's name that reads as a name in a sentence: no nickname in quotes, no note, no company. PLAIN_AUTHOR = re.compile(r"[^\"();]{1,40}") # A designation that is only a kind of trail and a year: "National Scenic Trail (1968)". DESIGNATION_YEAR = re.compile(r"^(National [A-Z][a-z]+ Trail) \((?:(designated|certified) )?(\d{4})\)$") GPX_CLAUSE = { "here": "this page has a GPX of the track to download", "partial": "this page has a GPX of part of the track to download", "free": "its author publishes a GPX free of charge, which this site does not host", "sold": "its author sells a GPX, which this site does not host", "unpublished": "no GPX of it is published", } def gpx_clause(rec): """The clause of the "In brief" paragraph about the GPX; "" when the status has none.""" status = facets.gpx(rec) if status == "sold" and not common.sells_gpx(rec): return "its author sells it as a guide, and this site has no GPX for it" return GPX_CLAUSE.get(status, "") def _name_html(rec): """The name for the start of a sentence: "The Appalachian Trail", with no "The" before a name that has one or is not in English; marked with its language when it is not English.""" plain = common.plain_name(rec) lang = rec.get("derived", {}).get("name_lang", "") if rec.get("common_name") or not lang: text = esc(plain) else: text = f'{esc(plain)}' if lang or plain.lower().startswith("the "): return Markup(text) return Markup("The " + text) MAX_BRIEF = 4 # sentences in the "In brief" paragraph 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) def season_sentence(rec): """("range", "The usual season is May to July") for a season that is a range of months or 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.""" text = facets.season_text(rec).strip().rstrip(". ") if not text: return None if re.search(r"[;:]", text): # "Spring and fall; summers tend to be humid": the range, then a note head = re.split(r"[;:]", text, maxsplit=1)[0].strip() if not SENTENCE_VERBS.search(head) or len(text) > 110: text = head if len(text) > 110: # a long note that does not break at a clause stays in "At a glance" return None if text.lower() == "all year": return ("sentence", "It can be walked all year") if SENTENCE_VERBS.search(text) and not text.lower().startswith(("from", "about", "early", "late", "mid")) or \ text.split()[0].lower() in ("northbound", "the", "best", "hikers"): return ("sentence", text[:1].upper() + text[1:]) first = text.split()[0].lower().split("-")[0] if first in SEASON_WORDS: text = text[:1].lower() + text[1:] return ("range", f"The usual season is {text}") def permit_sentence(rec): """The record's permit text as one sentence, when it is short and says one thing; else "".""" text = common.sentence(hike.table(rec).get("permit", "")) if not text or len(text) > 75 or text.count(".") > 1 or ";" in text: return "" return text def built_clause(rec): """", with about 290 miles (467 km) built" for an unfinished trail whose holder states the built length; else "". HTML-safe text.""" if not rec.get("built_km"): return "" mi = words.fmt_int(words.km_to_mi(rec["built_km"])) return f", with {esc(mi)} miles ({esc(words.fmt_km(rec['built_km']))} km) built" def brief_sentences(rec): """The "In brief" paragraph as a list of sentences in HTML, from the record's own fields only. A fact the record lacks is left out. At most MAX_BRIEF sentences, in the order a searcher wants them: what it is and where, how long and how long it takes, the highest point and climb, when to go, and whether there is a GPX. Facts that do not fit stay in "At a glance".""" h = hike.table(rec) route = common.is_route(rec) shape = facets.shape(rec) mi = words.fmt_int(rec["derived"]["length_mi"]) km = words.fmt_km(rec["length_km"]) terrain = [TERRAIN_ADJECTIVE[t] for t in facets.terrain(rec)] walking = facets.walking(rec) country = f"{words.join_names(terrain)} country" if terrain else "" items = [] # (priority, display position, sentence); the lowest priorities are kept # What it is, how long, where. tail = "" name = common.plain_name(rec) if route: who, year = facets.author(rec), rec.get("route", {}).get("year") if not PLAIN_AUTHOR.fullmatch(who or "") or who.lower().startswith("the "): who = "" # a nickname, a company or a note: the line under the heading names the author in full noun = f"{'loop ' if shape == 'loop' else ''}route" if shape != "network" else "route network" noun += f" by {who}" if who else "" tail = f", dating from {year}," if who and year else "" else: found = DESIGNATION_YEAR.match(rec.get("designation", "").strip()) noun = {"loop": "loop trail", "network": "trail network"}.get(shape, "trail") if found: # "National Scenic Trail (1968)": the kind and the year, unless the name already says the kind if found.group(1).lower() not in name.lower(): noun = found.group(1) tail = f", {found.group(2) or 'designated'} in {found.group(3)}," article = "an" if mi.startswith("8") else "a" # "an 81-mile", "an 800-mile" through = f" through {country}" if country else "" items.append((0, 0, f"{_name_html(rec)} is {article} {esc(mi)}-mile ({esc(km)} km) {esc(noun)}" f"{esc(tail)}{esc(through)} {esc(place_text(rec))}{built_clause(rec)}.")) unfinished = common.sentence(h.get("unfinished", "")) if unfinished and unfinished not in hike.summary(rec): # the lede above may already say it items.append((4, 1, esc(unfinished))) # Where it starts and ends, and how long it usually takes. start, end = h.get("start", ""), h.get("end", "") days = hike.days(rec) # A place name that starts a sentence in the record reads mid-sentence in lower case. mid = lambda text: text[:1].lower() + text[1:] if text.startswith(("The ", "Near ")) else text # noqa: E731 at = lambda text: "near " + text[5:] if text.startswith("Near ") else "at " + text # noqa: E731 from_start, to_end = mid(start), mid(end) if shape == "loop": where = f"It starts and ends {at(start)}" if start else "" elif shape == "network": where = f"Most walks start {at(start)}" if start else "" elif start and end: where = f"It runs from {from_start}{',' if ',' in start else ''} to {to_end}" elif start: where = f"It starts {at(start)}" elif end: where = f"It ends {at(end)}" else: where = "" if where and days: items.append((1, 2, f"{esc(where)}, and walking all of it usually takes {esc(days)}.")) elif where: items.append((1, 2, f"{esc(where)}.")) elif days: items.append((1, 2, f"Walking all of it usually takes {esc(days)}.")) # What the walking is. if walking and walking != "trail": # the usual case needs no sentence items.append((5, 3, esc(WALKING_ALONE[walking]))) # Highest point and climb, with the record's own caveat where the figures come from the track. elev = elevation.get(rec) high_name, high_m = h.get("high_point", ""), h.get("high_point_m") high = "" if high_name.startswith(("Near ", "Between ", "Above ", "Along ")): high_name = high_name[:1].lower() + high_name[1:] # "Its highest point is near Owen Creek" if high_name and high_m: high = f"{high_name}, at {elevation.plain_elevation(high_m)}" elif high_name: high = high_name elif high_m: high = elevation.plain_elevation(high_m) climb = f"the track climbs {elevation.plain_elevation(elev['ascent_m'])} in total" if elev else "" how = "computed from the track" if elev and elevation.coverage_kind(elev) == "partial": how = (f"computed from the part of the track on file, {elevation.coverage_percent(elev)} " f"of the published length") elif elev and elevation.coverage_kind(elev) == "over": how = (f"computed from a track longer than the published length " f"({elevation.coverage_percent(elev)} of it), so the climb is overstated") if high and climb: items.append((2, 4, f"Its highest point is {esc(high)}, and {esc(climb)}, {esc(how)}.")) elif high: items.append((2, 4, f"Its highest point is {esc(high)}.")) elif elev: items.append((2, 4, f"Its highest point is {esc(elevation.plain_elevation(elev['highest']['m']))}, " f"and {esc(climb)}, {esc(how)}.")) # 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]): # "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]) + ".")) 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]) return [text for _, _, text in kept] def brief(rec, label=True): """The "In brief" paragraph of a trail: Markup. label: it opens with "In brief." (a trail page has its own "In brief" heading over it and leaves the label out).""" lead = "In brief. " if label else "" return Markup(f'

{lead}{" ".join(brief_sentences(rec))}

') def checked_line(rec): """"Last checked 2026-11-08", as a