diff --git a/glossary.toml b/glossary.toml index e48cb61..a89aef0 100644 --- a/glossary.toml +++ b/glossary.toml @@ -116,7 +116,7 @@ see = ["/lists/weekend/", "/lists/one-to-two-weeks/", "/lists/a-month-or-more/", [[term]] id = "season" term = "Season" -definition = "The months in which the whole trail is usually walked, as a source states them. It is not the dates a park or a hut is open. Only some records state one." +definition = "The months in which the whole trail is usually walked. Where a page states them, that is shown. Otherwise they are estimated from the climate at the trail's elevation and from similar trails, and the page says so: an estimated season reads “About” with a note. It is not the dates a park or a hut is open." see = ["/lists/"] [[term]] diff --git a/web/assets/app.js b/web/assets/app.js index dce1f5e..f4d2be8 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -1940,9 +1940,10 @@ var OLD_POLICY = { open: 'free', sold: 'sold', withheld: 'unpublished', unclear: 'elsewhere' }; /* facet-counts:begin — pure, with no page: web/tests/test_filter_counts.py runs this under node. - A row: {search: [name, author, places, summary], where: [], km, time, months: [], terrain: [], kind, walking, shape, gpx}. - A state: {words: [], where, min, max (km; max may be Infinity), month, kind, and a list for - each of time, terrain, walking, shape, gpx}. */ + A row: {search: [name, author, places, summary], where: [], km, time, months: [], estimate, terrain: [], kind, walking, shape, gpx}. + A state: {words: [], where, min, max (km; max may be Infinity), month, stated, kind, and a list for + each of time, terrain, walking, shape, gpx}. stated: with a month chosen, leave out the rows whose + season is an estimate. */ var FacetCount = (function () { var FACETS = ['where', 'length', 'time', 'month', 'terrain', 'kind', 'walking', 'shape', 'gpx']; function has(list, v) { return list.indexOf(v) !== -1; } @@ -1991,6 +1992,9 @@ if (skip !== 'length' && (d.km < s.min || d.km > s.max)) return false; if (skip !== 'time' && s.time.length && !has(s.time, d.time)) return false; if (skip !== 'month' && s.month && !has(d.months, s.month)) return false; + /* Leaving estimates out belongs to the month: it holds in counting each month too, so the + number beside a month is what choosing it, with estimates left out, shows. */ + if (s.month && s.stated && d.estimate) return false; if (skip !== 'terrain' && s.terrain.length && !d.terrain.some(function (t) { return has(s.terrain, t); })) return false; if (skip !== 'kind' && s.kind && d.kind !== s.kind) return false; if (skip !== 'walking' && s.walking.length && !has(s.walking, d.walking)) return false; @@ -2052,15 +2056,14 @@ var rows = Array.prototype.map.call(resultsRoot.querySelectorAll('.entry[data-id]'), function (li) { var d = li.dataset; return { li: li, id: d.id, search: FacetCount.textsOf(d.search), where: split(d.where), km: Number(d.km), time: d.time || '', - months: split(d.months), terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '', + months: split(d.months), estimate: d.estimate === 'yes', terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '', shape: d.shape || '', gpx: d.gpx || '' }; }); var lists = Array.prototype.slice.call(resultsRoot.querySelectorAll('ol.entries')); var count = resultsRoot.querySelector('.results-count'); var noun = (count && count.dataset.noun) || 'trails'; var empty = resultsRoot.querySelector('.empty-state'); - var unseasoned = resultsRoot.querySelector('[data-unseasoned]'); - var unseasonedText = resultsRoot.querySelector('[data-unseasoned-text]'); + var seasonAlways = resultsRoot.hasAttribute('data-season-shown'); var active = form.querySelector('.filters__active'); var lenHint = document.getElementById('len-hint'); var listHead = resultsRoot.querySelector('.list-head'); @@ -2160,6 +2163,7 @@ maxRaw: maxRaw, swapped: swapped, month: value(el.month), + stated: !!(el.stated && el.stated.checked && value(el.month)), kind: radio('kind') }; MULTI.forEach(function (name) { s[name] = checked(name); }); @@ -2287,6 +2291,7 @@ if (s.min) p.set('min', s.minRaw); if (s.max !== Infinity) p.set('max', s.maxRaw); if (s.month) p.set('month', s.month); + if (s.month && s.stated) p.set('stated', '1'); if (s.kind) p.set('kind', s.kind); MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); }); if (sort && sort.value !== defaultSort && sort.value !== 'nearest') p.set('sort', sort.value); @@ -2332,6 +2337,7 @@ if (el.month) { var month = p.get('month') || ''; el.month.value = hasOption(el.month, month) ? month : ''; + if (el.stated) el.stated.checked = !!el.month.value && p.get('stated') === '1'; } var kind = p.get('kind') || ''; if (kind === 'designated') kind = 'trail'; @@ -2460,16 +2466,19 @@ count.appendChild(document.createTextNode(' ' + words)); } if (empty) empty.hidden = shown.length > 0; - /* With a month chosen, say how many trails that pass everything else are left out for having no - season on file, counted over the same rows as the list. */ - if (unseasoned && el.month) { - var noSeason = 0; - if (s.month) rows.forEach(function (d) { if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++; }); - unseasoned.hidden = noSeason === 0; - if (noSeason) { - unseasonedText.textContent = noSeason + (noSeason === 1 ? ' trail with no season on file is not shown.' - : ' trails with no season on file are not shown.'); + /* A month's rows show their season, and the way to leave estimated seasons out is offered once a + month is chosen and some of the trails that pass everything else have an estimated season. */ + if (!seasonAlways) resultsRoot.toggleAttribute('data-season-shown', !!s.month); + if (el.stated) { + var open = false; + if (s.month) { + var withEstimates = Object.assign({}, s, { stated: false }); + open = rows.some(function (d) { return d.estimate && FacetCount.passes(d, withEstimates, ''); }); } + el.stated.disabled = !s.month; + if (!s.month) el.stated.checked = false; + var box = el.stated.closest('label'); + if (box) box.hidden = !open && !el.stated.checked; } if (listHead) listHead.hidden = shown.length === 0; relabel(s, c); @@ -2499,14 +2508,6 @@ form.addEventListener('change', function () { apply(true); }); form.addEventListener('submit', function (e) { e.preventDefault(); }); form.addEventListener('reset', function () { setTimeout(function () { apply(true); }, 0); }); - resultsRoot.querySelectorAll('[data-unseasoned-show]').forEach(function (b) { - /* Showing them is clearing the month; the rest of the filters stay. */ - b.addEventListener('click', function () { - if (!el.month) return; - el.month.value = ''; - el.month.dispatchEvent(new Event('change', { bubbles: true })); - }); - }); resultsRoot.querySelectorAll('[data-reset]').forEach(function (b) { b.addEventListener('click', function () { form.reset(); el.q.focus(); }); }); diff --git a/web/assets/style.css b/web/assets/style.css index 342659e..9f1ce6e 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -1247,6 +1247,11 @@ html.js .filters__panels:not([data-open]) { display: none; } .results-note { margin-block: calc(-1 * var(--space-1)) var(--space-3); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); } .results-note[hidden] { display: none; } .results-note__show { padding: 0; border: 0; background: none; color: var(--link); font: inherit; text-decoration: underline; cursor: pointer; } +/* A row's season: shown on a month's list, and while a month is chosen (app.js). */ +.entry__season { display: none; } +[data-season-shown] .entry__season { display: block; } +.field__check { display: block; margin-block-start: var(--space-1); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); } +.field__check[hidden] { display: none; } .key { display: flex; flex-wrap: wrap; diff --git a/web/olt/browse.py b/web/olt/browse.py index c8e08e3..fb66b42 100644 --- a/web/olt/browse.py +++ b/web/olt/browse.py @@ -78,7 +78,7 @@ GROUPS = ( ("walking", "By kind of walking", "Loops, high routes, walking with no trail, and trails not yet finished."), ("terrain", "By terrain", "The main kinds of country a trail crosses."), ("holder", "By who looks after it", "Trails whose designation names the holder."), - ("month", "By month", "Trails whose season on file includes the month. Only some trails have a season."), + ("month", "By month", "Trails normally hiked in the month. Estimated seasons are marked."), ("where", "By country and GPX", "Where a trail is, and whether its page has a track to download."), ) @@ -115,7 +115,7 @@ def time_note(recs, records): def _month_list(m): name = facets.MONTHS[m - 1] return List(f"hike-in-{name.lower()}", f"Hiking in {name}", - f"Trails whose season on file includes {name}.", + f"Trails normally hiked in {name}. Estimated seasons are marked.", lambda r, m=m: m in facets.months(r), page_title=f"Long Trails to Hike in {name}: {{n}} Trails", group="month", note=month_note(name), min_size=MONTH_MIN) @@ -123,9 +123,14 @@ def _month_list(m): def month_note(name): def note(recs, records): - have = sum(1 for r in records if facets.months(r)) - return (f"Only {have} of the {len(records)} trails have a season on file, so this page covers those " - f"{have}. It is not every trail that can be walked in {name}.") + est = sum(1 for r in recs if facets.season_estimated(r)) + stated = len(recs) - est + if not est: + return f"A source states the season for all {stated}." + if not stated: + return "No source states the season for these, so each is estimated from climate." + return (f"A source states the season for {stated} of these. For the other {est} it is " + f"estimated from climate, and marked.") return note diff --git a/web/olt/datafiles.py b/web/olt/datafiles.py index aeb9180..c648570 100644 --- a/web/olt/datafiles.py +++ b/web/olt/datafiles.py @@ -4,11 +4,13 @@ collections.toml [[collection]] named sets of trails set side by side (olt/standing.py) [[list]] which lists the home page shows, and in what order (olt/home.py) authors.toml [[author]] route authors, and the words about the people among them (olt/authors.py) + tools/season_blind_test.json how the judged seasons did against the seasons pages state (olt/reference.py) Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file is looked for in the repository being built and then in this one, so a test repository without one still builds. """ +import json import os import tomllib @@ -40,3 +42,14 @@ def authors(repo_root): def lists(repo_root): """The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row.""" return load(repo_root, "collections.toml", "list") + + +def blind_test(repo_root): + """The blind test of the judged seasons (tools/season_blind_test.json, written by + tools/season_judge.py score), or None when there is none.""" + for base in (repo_root, REAL_ROOT): + path = os.path.join(base or REAL_ROOT, "tools", "season_blind_test.json") + if os.path.isfile(path): + with open(path, encoding="utf-8") as f: + return json.load(f) + return None diff --git a/web/olt/facets.py b/web/olt/facets.py index 5410974..44723c0 100644 --- a/web/olt/facets.py +++ b/web/olt/facets.py @@ -172,8 +172,15 @@ def months(rec): return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12}) -def season_text(rec): - """The phrase on the trail page: [hike].season, else built from the months.""" +def season_estimated(rec): + """True when no page states the season: it was estimated (season_basis "estimate"), or set by + judgement from pages that differ (it carries a season_method). Such a season reads "About".""" + h = hike.table(rec) + return bool(h.get("season")) and (h.get("season_basis") == "estimate" or bool((h.get("season_method") or "").strip())) + + +def season_phrase(rec): + """The phrase on the trail page as the record gives it: [hike].season, else built from the months.""" phrase = (hike.table(rec).get("season") or "").strip() if phrase: return phrase[:1].upper() + phrase[1:] @@ -185,6 +192,74 @@ def season_text(rec): return words.join_names(MONTHS[m - 1] for m in ms) +def season_text(rec): + """The season as a page shows it: the phrase, or "About ..." where it is estimated, so an + estimate never reads as a stated fact ("About June to September", "About all year").""" + phrase = season_phrase(rec) + if not phrase or not season_estimated(rec): + return phrase + if phrase.lower().startswith("about"): + return phrase + if phrase.lower() == "all year": + phrase = phrase.lower() + return "About " + phrase + + +def season_kind(rec): + """How the season is known: "stated" (a page states it), "judged" (set by judgement from pages + that differ), "estimated" (no page states one), or "" when the trail has no season.""" + if not hike.table(rec).get("season"): + return "" + if not season_estimated(rec): + return "stated" + return "judged" if season_basis(rec) == "sources" else "estimated" + + +SEASON_CONFIDENCE = re.compile(r"\s*Confidence: (high|medium|low)\.\s*$") +JUDGED_LEAD = "Judged from the climate at the trail's elevation and from similar trails." + + +def season_confidence(rec): + """"high", "medium" or "low" from the end of the season's method; "" when it names none.""" + found = SEASON_CONFIDENCE.search(hike.table(rec).get("season_method") or "") + return found.group(1) if found else "" + + +def season_reason(rec): + """What the season's method says sets the season, without its standard first sentence and its + closing confidence.""" + text = SEASON_CONFIDENCE.sub("", (hike.table(rec).get("season_method") or "").strip()).strip() + if text.startswith(JUDGED_LEAD): + text = text[len(JUDGED_LEAD):].strip() + return text + + +def season_pages_differ(rec): + """True for a season set by judgement from pages that state different seasons.""" + return season_estimated(rec) and season_basis(rec) == "sources" + + +def season_note(rec): + """Says an estimated season is not a page's statement, how it was worked out, what sets it + there and how far to trust it; "" when a page states the season.""" + if not season_estimated(rec): + return "" + reason = season_reason(rec) + if season_pages_differ(rec): + lead = "No one page states this season." + else: + lead = ("No page states a season. This is estimated from the climate at the trail's " + "elevation and from similar trails.") + parts = [lead] + if reason: + parts.append(reason) + conf = season_confidence(rec) + if conf: + parts.append(f"Confidence: {conf}.") + parts.append("People do walk it outside these months.") + return " ".join(parts) + + SEASON_BASIS_TEXT = { "primary": "The season comes from the page of the body that manages the trail or the trail's own association or, for a route, its author.", "sources": "Two or more pages from different publishers agree on the season.", @@ -203,10 +278,12 @@ def season_basis(rec): def season_basis_line(rec): """One sentence for "About this data"; "" when the season has no recorded basis.""" basis = season_basis(rec) - if basis == "estimate": - method = (hike.table(rec).get("season_method") or "").strip() - return (method + " No page states a season.").strip() - return SEASON_BASIS_TEXT.get(basis, "") + if not season_estimated(rec): + return SEASON_BASIS_TEXT.get(basis, "") + method = (hike.table(rec).get("season_method") or "").strip() + if season_pages_differ(rec): + return (method + " It is a judgement, not any one page's statement.").strip() + return (method + " No page states a season.").strip() # Terrain, Walking, Shape ---------------------------------------------------- diff --git a/web/olt/home.py b/web/olt/home.py index 508acae..d920161 100644 --- a/web/olt/home.py +++ b/web/olt/home.py @@ -193,6 +193,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals if search: data["search"] = searchtext.attribute(rec) attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items()) + estimated = facets.season_estimated(rec) + if estimated: + attrs += ' data-estimate="yes"' if common.line_differs(rec): attrs += ' data-partial="yes"' h = f"h{level}" @@ -203,6 +206,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals desc = entry_desc(rec) desc_html = f'\n
{esc(desc)}
' if desc else "" time_html = esc(facets.time_text(rec)) + (' estimate' if est else "") + season_html = (f'\nTrails usually walked in that month.
+Trails usually walked in that month. Estimated seasons are marked.
{stated_box} {_missing(records, "season")}' - '
' - if finder else "") - return Markup(f"""Every trail has a season. Where a page states one, the season is that page’s. Where the pages that state one differ and none is the trail’s holder, its association or its route’s author, the season is set by judgement from all of them and the climate, and the page says so. Where no page states one, the season is estimated from the climate at the trail’s elevation and from similar trails: it reads “About” with a note, is marked in lists and is left out of the data search engines read. People do walk many trails outside their estimated months, and an estimate is replaced when a page that states a season is found.
+ {pagekit.table(["Where a trail's season comes from", "Trails"], rows, caption="Where the seasons come from", numeric=(1,))}"""] + if blind: + by = blind["by_confidence"] + conf = ", ".join(f"{name} {by[name]['matched']} of {by[name]['tested']} ({_pct(by[name]['share'])})" + for name in ("high", "medium", "low") if by[name]["tested"]) + out.append(f"""How the estimates were tested. On {esc(blind["date"])} the method was run blind on {blind["tested"]} trails whose seasons a page does state, with those seasons hidden. It matched {blind["matched"]} of them ({_pct(blind["share"])}) within one month at each end of the season the page states. By the confidence it gave each estimate: {esc(conf)}. This measures how the method did where the answer is known, not a promise for any one trail.
""") + return "\n ".join(out) + + def method_page(records, site, repo_root): """(title, description, body) for /method/.""" meaning = schema_meanings(repo_root) @@ -120,12 +146,15 @@ def method_page(records, site, repo_root): (a, b), (c, d_) = facets.PACE_KM, facets.PACE_KM_CROSS coverage = [] for label, fn in (("A usual time stated by a source", lambda r: not facets.time_days(r)[2]), - ("A season", lambda r: bool(facets.months(r))), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))), + ("A season a page states", lambda r: facets.season_kind(r) == "stated"), + ("A season set from pages that differ", lambda r: facets.season_kind(r) == "judged"), + ("A season estimated from climate", lambda r: facets.season_kind(r) == "estimated"), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))), ("Terrain", lambda r: bool(facets.terrain(r))), ("What the walking is", lambda r: bool(facets.walking(r))), ("A computed climb that covers the whole trail", lambda r: facets.row_climb_m(r) is not None), ("A track included here", common.has_line)): have = sum(1 for r in records if fn(r)) coverage.append([label, str(have), str(n - have)]) + season_html = season_section(records, datafiles.blind_test(repo_root)) rows = [[label, str(k), f"{k / len(ver) * 100:.0f}%" if ver else ""] for label, k in bands] body = (pagekit.head("How the figures are measured", ( f"What each figure on this site means, and how far to trust it. {len(ver)} of the {n} trails have a track whose " @@ -145,7 +174,8 @@ def method_page(records, site, repo_root):Climb is the total ascent along the track.{(" It uses " + esc(model) + ", sampled every " + words.fmt_int(spacing) + " metres, with " + esc(smoothing[:1].lower() + smoothing[1:]) + ".") if model and spacing else ""} {esc(limits_text)}
A climb is ranked or shown in a list only where its track covers the whole trail: a track that covers part of the trail, or more than the trail, would mislead.
{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} Not every record has them, so a page built from them says how many records it covers.
+{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))}
+ {season_html}Every fact is read on a page that the record names. See the sources, the record schema and the glossary.
diff --git a/web/olt/regions.py b/web/olt/regions.py index a9008be..0ec6b41 100644 --- a/web/olt/regions.py +++ b/web/olt/regions.py @@ -390,7 +390,7 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead{esc(note.strip())}
' if note else ''}{rule}
", about_title="About this list")} diff --git a/web/olt/seo.py b/web/olt/seo.py index f61744b..d6abd26 100644 --- a/web/olt/seo.py +++ b/web/olt/seo.py @@ -284,7 +284,8 @@ def _properties(rec): props.append(_pv("Shape", facets.SHAPES[shape])) props.append(_pv("Start", h.get("start", "")) if h.get("start") else None) props.append(_pv("End", h.get("end", "")) if h.get("end") else None) - props.append(_pv("Usual season", h["season"]) if h.get("season") else None) + # Only a season a page states: an estimate is not a fact about the trail to hand to a search engine. + props.append(_pv("Usual season", h["season"]) if h.get("season") and not facets.season_estimated(rec) else None) if common.is_route(rec): route = rec.get("route", {}) props.append(_pv("Route author", route["creator"]) if route.get("creator") else None) diff --git a/web/olt/standing.py b/web/olt/standing.py index 19b5f11..de0f2e5 100644 --- a/web/olt/standing.py +++ b/web/olt/standing.py @@ -45,14 +45,16 @@ def time_cell(rec): def season_cell(rec): - return facets.season_text(rec) or "Not on file" + return facets.season_text(rec) def figures_note(recs): """What the times and climbs of these trails mean, with the caveats the records state.""" est = sum(1 for r in recs if facets.time_days(r)[2]) + unstated = sum(1 for r in recs if facets.season_estimated(r)) parts = [f"Times that start with “About” are estimated from the length ({est} of these). " "Otherwise a source states the time.", + f"Seasons that start with “About” are estimated from climate ({unstated} of these)." if unstated else "", climb_caveat(recs)] return " ".join(p for p in parts if p) diff --git a/web/olt/summary.py b/web/olt/summary.py index 242f2da..9a41fe4 100644 --- a/web/olt/summary.py +++ b/web/olt/summary.py @@ -148,7 +148,9 @@ def detail(rec): out.append(f"Its high point is {esc(name + ', ') if name else ''}{words.elevation(m)}.") season = facets.season_text(rec) if season: - out.append(f"Season: {esc(season)}.") + how = (", judged from pages that differ" if facets.season_pages_differ(rec) + else ", estimated from climate" if facets.season_estimated(rec) else "") + out.append(f"Season: {esc(season)}{how}.") rest = _rest_of_summary(rec) if rest: out.append(f'{esc(rest)}') diff --git a/web/olt/trail.py b/web/olt/trail.py index 21e3391..5a5f11f 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -282,6 +282,7 @@ def _name_html(rec): MAX_BRIEF = 4 # sentences in the "In brief" paragraph +PINNED = -1 # the priority of a sentence that is kept besides those (an estimated season) MONTH_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") SEASON_WORDS = ("spring", "summer", "fall", "autumn", "winter", "late", "early", "mid", "from", "about") SENTENCE_VERBS = re.compile(r"\b(is|are|can|start|starts|hikes?|hiked|travelled|traveled|bring|brings|closed|best)\b", re.I) @@ -292,6 +293,13 @@ def season_sentence(rec): seasons, ("sentence", "Northbound hikes start late February to early April") for one the record already words as a sentence, or None when the record has none or it is too long to say briefly. The caller adds the full stop. Only the record's own words are used.""" + if facets.season_estimated(rec): + # Never worded as a fact, and never joined to the GPX clause with "and". + phrase = facets.season_phrase(rec).rstrip(". ") + phrase = phrase.lower() if phrase.lower() == "all year" else phrase + if facets.season_pages_differ(rec): + return ("estimate", f"The pages differ on the season; it is judged to be about {phrase}") + return ("estimate", f"No source gives a season; the climate suggests about {phrase}") text = facets.season_text(rec).strip().rstrip(". ") if not text: return None @@ -431,19 +439,23 @@ def brief_sentences(rec): # When to walk it and whether this site has a GPX: one sentence where the season is a plain range. clause = gpx_clause(rec) or ("this site has no GPX for it" + _see_clause(rec)) season = season_sentence(rec) - if season and not re.search(r"[,;]", season[1]): + if season and season[0] != "estimate" and not re.search(r"[,;]", season[1]): # "The usual season is May to July, and this page has a GPX of the track to download." items.append((3, 5, f"{esc(season[1])}, and {esc(clause)}.")) else: if season: - items.append((3.5, 5, esc(season[1]) + ".")) + # An estimated season is always said, so it is never left for a reader to take as a fact + # by omission: it is the one sentence that may stand beyond MAX_BRIEF. + items.append((PINNED if season[0] == "estimate" else 3.5, 5, esc(season[1]) + ".")) items.append((3, 6, esc(clause[:1].upper() + clause[1:]) + ".")) permit = permit_sentence(rec) if permit: items.append((6, 7, esc(permit))) # At most MAX_BRIEF sentences: the lowest priorities are kept, shown in reading order. - kept = sorted(sorted(items, key=lambda i: (i[0], i[1]))[:MAX_BRIEF], key=lambda i: i[1]) + pinned = [i for i in items if i[0] == PINNED] + rest = sorted((i for i in items if i[0] != PINNED), key=lambda i: (i[0], i[1]))[:MAX_BRIEF] + kept = sorted(rest + pinned, key=lambda i: i[1]) return [text for _, _, text in kept] @@ -624,7 +636,7 @@ def glance(rec, records=None): rows.append(glance_row(facets.TIME, facets.time_text(rec), time_note(rec, records))) season = facets.season_text(rec) if season: - rows.append(glance_row(facets.SEASON, season)) + rows.append(glance_row(facets.SEASON, season, facets.season_note(rec))) if facets.walking(rec): walking = facets.WALKING_VALUES[facets.walking(rec)] if facets.walking(rec) in facets.CROSS_COUNTRY: @@ -692,7 +704,7 @@ def glance(rec, records=None): unfinished = "" if h.get("unfinished"): unfinished = f'Not finished. {common.rich(common.sentence(h["unfinished"]))}
' - missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain), + missing = [name for name, have in ((facets.TERRAIN, terrain), (facets.WALKING, facets.walking(rec)), (PERMITS, h.get("permit"))) if not have] pending = "" diff --git a/web/tests/test_facets.py b/web/tests/test_facets.py index b1cbb9d..8255463 100644 --- a/web/tests/test_facets.py +++ b/web/tests/test_facets.py @@ -173,6 +173,59 @@ class PlaceTest(unittest.TestCase): self.assertIn('Colorado', crumbs) +def est_hike(**kw): + h = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate", + "season_method": "Judged from the climate at the trail's elevation and from similar trails. " + "Snow keeps the high passes closed until June. Confidence: medium."} + h.update(kw) + return h + + +class SeasonTextTest(unittest.TestCase): + def test_an_estimated_season_reads_about_and_has_a_note(self): + rec = fake(1, hike=est_hike()) + self.assertTrue(facets.season_estimated(rec)) + self.assertEqual(facets.season_text(rec), "About June to September") + note = facets.season_note(rec) + for want in ("No page states a season", "estimated from the climate at the trail's elevation and from " + "similar trails", "Snow keeps the high passes closed until June.", "Confidence: medium.", + "People do walk it outside these months."): + self.assertIn(want, note) + self.assertNotIn("Judged from", note) # the standard lead is said once, in the note's own words + + def test_a_stated_season_is_unchanged_and_has_no_note(self): + rec = fake(1, hike={"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "primary"}) + self.assertFalse(facets.season_estimated(rec)) + self.assertEqual(facets.season_text(rec), "June to September") + self.assertEqual(facets.season_note(rec), "") + + def test_an_estimated_all_year_season_reads_about_all_year(self): + rec = fake(1, hike=est_hike(season="All year", months=list(range(1, 13)))) + self.assertEqual(facets.season_text(rec), "About all year") + + def test_it_is_not_estimated_without_a_basis_or_a_method(self): + self.assertFalse(facets.season_estimated(fake(1, hike={"season": "May", "months": [5]}))) + self.assertFalse(facets.season_estimated(fake(1))) + self.assertEqual(facets.season_kind(fake(1)), "") + + def test_a_season_judged_from_pages_that_differ_says_so(self): + rec = fake(1, hike=est_hike(season_basis="sources", season_method=( + "The pages differ: one gives May to October and one gives June to November. It was set by " + "judgement from both and from the climate. Confidence: medium."))) + self.assertTrue(facets.season_estimated(rec)) + self.assertEqual(facets.season_kind(rec), "judged") + self.assertEqual(facets.season_text(rec), "About June to September") + note = facets.season_note(rec) + self.assertIn("No one page states this season.", note) + self.assertIn("The pages differ", note) + self.assertNotIn("estimated from the climate at the trail's elevation", note) + self.assertIn("It is a judgement", facets.season_basis_line(rec)) + + def test_the_basis_line_gives_the_method_for_an_estimate(self): + line = facets.season_basis_line(fake(1, hike=est_hike())) + self.assertTrue(line.endswith("Confidence: medium. No page states a season."), line) + + class MissingValuesTest(unittest.TestCase): def recs(self, n_with, n_without): return ([fake(i, hike={"months": [7, 8], "season": "July and August", "terrain": ["alpine"]}) @@ -189,22 +242,24 @@ class MissingValuesTest(unittest.TestCase): self.assertIn('name="terrain"', form) def test_missing_count_is_said(self): + # the generic mechanism, shown with terrain: no real trail lacks a season any more form = home.finder_form(self.recs(10, 12)) - self.assertIn('data-missing="season" hidden>12 trails have no season on file.', form) self.assertIn('data-missing="terrain" hidden>12 trails have no terrain on file.', form) - self.assertEqual(facets.missing_text(1, "season"), "1 trail has no season on file.") - self.assertEqual(facets.missing_text(0, "season"), "") + self.assertEqual(facets.missing_text(1, "terrain"), "1 trail has no terrain on file.") + self.assertEqual(facets.missing_text(0, "terrain"), "") # full coverage: no note - self.assertNotIn('data-missing="season"', home.finder_form(self.recs(5, 0))) + self.assertNotIn('data-missing="terrain"', home.finder_form(self.recs(5, 0))) def test_rows_without_a_value_carry_none(self): - # the script leaves out a row whose data-months is empty while a month is chosen row = home.entry(fake(1)) - self.assertIn('data-months=""', row) self.assertIn('data-terrain=""', row) row = home.entry(fake(1, hike={"months": [7, 8, 9]})) self.assertIn('data-months="7 8 9"', row) + def test_every_real_trail_has_months(self): + for rec in records.load_records(ROOT): + self.assertTrue(facets.months(rec), rec["id"]) + def test_script_leaves_out_missing_values(self): with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f: js = f.read() @@ -287,6 +342,31 @@ class BuiltVocabularyTest(unittest.TestCase): self.maxDiff = None self.assertEqual(bad[:40], []) + def test_no_page_says_only_some_trails_have_a_season(self): + found = [] + for dirpath, _dirs, files in os.walk(OUT): + for name in files: + if name.endswith(".html") and "changelog" not in dirpath: # its old entries say what was + path = os.path.join(dirpath, name) + with open(path, encoding="utf-8") as f: + doc = f.read() + for phrase in ("Only some trails have a season", "season on file", "Not on file", + "data-unseasoned", "Show them"): + if phrase in doc: + found.append((os.path.relpath(path, OUT), phrase)) + self.assertEqual(found[:10], []) + + def test_an_estimated_season_reads_about_on_its_page_and_a_stated_one_does_not(self): + est = [r for r in records.load_records(ROOT) if facets.season_estimated(r)] + stated = [r for r in records.load_records(ROOT) if not facets.season_estimated(r)] + self.assertEqual(len(est) + len(stated), 223) + for rec in est[:10]: + doc = self.read(f"trails/{rec['id']}/index.html") + self.assertIn(facets.season_text(rec), html.unescape(doc), rec["id"]) + self.assertIn("People do walk it outside these months.", html.unescape(doc), rec["id"]) + for rec in stated[:10]: + self.assertNotIn("People do walk it outside these months.", html.unescape(self.read(f"trails/{rec['id']}/index.html"))) + def test_navigation_has_four_sections_and_saved(self): doc = self.read("index.html") nav = re.search(r'', doc).group(1) diff --git a/web/tests/test_filter_bar.py b/web/tests/test_filter_bar.py index e5538eb..84e9fb1 100644 --- a/web/tests/test_filter_bar.py +++ b/web/tests/test_filter_bar.py @@ -235,13 +235,13 @@ def rows_of(body): d = {k: html.unescape(v) for k, v in re.findall(r' data-([a-z]+)="([^"]*)"', attrs)} split = lambda v: [x for x in v.split(" ") if x] # noqa: E731 out.append({"id": d["id"], "search": [" " + t + " " for t in d["search"].split("|")], "where": split(d["where"]), "km": float(d["km"]), - "time": d["time"], "months": split(d["months"]), "terrain": split(d["terrain"]), + "time": d["time"], "months": split(d["months"]), "estimate": d.get("estimate") == "yes", "terrain": split(d["terrain"]), "kind": d["kind"], "walking": d["walking"], "shape": d["shape"], "gpx": d["gpx"]}) return out def state(**kw): - s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "kind": "", + s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "stated": False, "kind": "", "time": [], "terrain": [], "walking": [], "shape": [], "gpx": []} s.update(kw) return s @@ -366,45 +366,75 @@ class PanelInTheFlowTest(unittest.TestCase): self.assertIn("if (window.location.hash === '#filters') showPanels(true);", js) -class UnseasonedNoteTest(unittest.TestCase): - """A month filter says how many trails it leaves out for having no season on file.""" +class LeaveOutEstimatesTest(unittest.TestCase): + """The month filter can leave estimated seasons out, and says nothing about trails with no season.""" - def test_a_finder_list_has_the_note_and_it_starts_hidden(self): + def test_the_month_field_has_the_checkbox_and_it_starts_disabled(self): recs = recordsmod.load_records(ROOT) - body = str(home.results(recs, finder=True)) - self.assertIn('', body) - self.assertIn('data-unseasoned-show>Show them', body) - self.assertNotIn("data-unseasoned", str(home.results(recs))) + form = home.finder_form(recs) + field = form[form.index('data-facet="month"'):] + field = field[:field.index("