Merge main into places-ship-2
This commit is contained in:
commit
1fbcfd5021
126 files changed
+2076
-9
No files matched your search
@@ -0,0 +1,77 @@
|
||||
"""Season provenance checks for a trail record's [hike] table.
|
||||
|
||||
Python 3 standard library only. tools/validate.py imports this module; it
|
||||
must not import validate.py. The fields are documented in docs/schema.md.
|
||||
"""
|
||||
|
||||
BASES = ("primary", "sources", "source", "estimate")
|
||||
PROVENANCE_KEYS = frozenset({"season_basis", "season_method"})
|
||||
SEASON_REQUIRED = False
|
||||
|
||||
|
||||
def _naming(sources, fact):
|
||||
return [s for s in sources if isinstance(s, dict) and fact in (s.get("facts") or [])]
|
||||
|
||||
|
||||
def check_season(tid, hike, errors):
|
||||
"""Check season, months, season_basis and season_method agree."""
|
||||
has_season = "season" in hike
|
||||
has_months = "months" in hike
|
||||
has_basis = "season_basis" in hike
|
||||
has_method = "season_method" in hike
|
||||
basis = hike.get("season_basis")
|
||||
sources = hike.get("source") or []
|
||||
if not isinstance(sources, list):
|
||||
sources = []
|
||||
|
||||
if has_season != has_months:
|
||||
errors.append(f"{tid}: hike.season and hike.months must appear together")
|
||||
if not has_season:
|
||||
if SEASON_REQUIRED:
|
||||
errors.append(f"{tid}: hike.season is required")
|
||||
if has_basis:
|
||||
errors.append(f"{tid}: hike.season_basis must not be given without hike.season")
|
||||
if has_method:
|
||||
errors.append(f"{tid}: hike.season_method must not be given without hike.season")
|
||||
return
|
||||
|
||||
if not has_basis:
|
||||
errors.append(f"{tid}: hike.season_basis is required when hike.season is present")
|
||||
elif basis not in BASES:
|
||||
errors.append(
|
||||
f"{tid}: hike.season_basis must be one of {', '.join(BASES)}, not {basis!r}")
|
||||
|
||||
if basis == "estimate":
|
||||
method = hike.get("season_method")
|
||||
if not isinstance(method, str) or not method.strip():
|
||||
errors.append(f"{tid}: hike.season_method is required with season_basis \"estimate\"")
|
||||
elif len(method) >= 400:
|
||||
errors.append(f"{tid}: hike.season_method must be under 400 characters")
|
||||
elif has_method:
|
||||
errors.append(f"{tid}: hike.season_method is only given with season_basis \"estimate\"")
|
||||
|
||||
naming_season = _naming(sources, "season")
|
||||
if basis in ("primary", "source"):
|
||||
if not naming_season:
|
||||
errors.append(
|
||||
f"{tid}: hike.season_basis \"{basis}\" needs a [[hike.source]] naming season")
|
||||
elif basis == "source":
|
||||
publishers = {str(s.get("publisher", "")).strip().casefold()
|
||||
for s in naming_season}
|
||||
if len(publishers) != 1:
|
||||
errors.append(
|
||||
f"{tid}: hike.season_basis \"source\" needs exactly one publisher "
|
||||
"naming season (two or more is \"sources\")")
|
||||
elif basis == "sources":
|
||||
publishers = {str(s.get("publisher", "")).strip().casefold()
|
||||
for s in naming_season if str(s.get("publisher", "")).strip()}
|
||||
if len(publishers) < 2:
|
||||
errors.append(
|
||||
f"{tid}: hike.season_basis \"sources\" needs two sources from different "
|
||||
"publishers naming season")
|
||||
elif basis == "estimate":
|
||||
naming = {id(s) for s in _naming(sources, "season") + _naming(sources, "months")}
|
||||
if len(naming) != 1:
|
||||
errors.append(
|
||||
f"{tid}: hike.season_basis \"estimate\" needs exactly one source naming "
|
||||
"season or months")
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""List the trails with no season and split them into batches for researchers.
|
||||
|
||||
Python 3 standard library only. Run from the repository root:
|
||||
|
||||
python3 tools/season_batches.py [--n 10] [--dir DIR]
|
||||
|
||||
Writes <staging>/season/batches/season-NN.txt, one trail id per line, and prints
|
||||
the batch count and the number of trails. A batch holds trails of one region
|
||||
group; a group of more than the batch size is split, and a leftover of fewer
|
||||
than five joins a neighbouring batch that has room.
|
||||
See docs/superpowers/plans/2026-11-20-season-on-every-trail.md.
|
||||
"""
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import refresh # noqa: E402
|
||||
|
||||
# Ordered so that neighbouring groups are neighbours on the map.
|
||||
REGION_GROUPS = {
|
||||
"west coast": ("CA", "OR", "WA", "AK", "HI"),
|
||||
"interior west": ("ID", "NV", "UT"),
|
||||
"southwest": ("AZ", "NM", "TX"),
|
||||
"Rockies": ("CO", "WY", "MT"),
|
||||
"plains and midwest": ("ND", "SD", "NE", "KS", "OK", "MN", "IA", "MO", "WI", "IL", "IN", "MI", "OH"),
|
||||
"northeast": ("ME", "NH", "VT", "MA", "RI", "CT", "NY", "NJ", "PA", "DE", "MD", "DC", "WV"),
|
||||
"southeast": ("VA", "NC", "SC", "GA", "FL", "AL", "MS", "TN", "KY", "LA", "AR"),
|
||||
"Canada west": ("BC", "AB", "SK", "MB", "YT"),
|
||||
"Canada east and north": ("ON", "QC", "NB", "NS", "PE", "NL", "NT", "NU"),
|
||||
}
|
||||
OTHER = "other"
|
||||
MIN_BATCH = 5
|
||||
|
||||
|
||||
def group_of(rec):
|
||||
"""The region group of a record's first region code (OTHER when unknown)."""
|
||||
for code in rec.get("regions") or []:
|
||||
for name, codes in REGION_GROUPS.items():
|
||||
if code in codes:
|
||||
return name
|
||||
break
|
||||
return OTHER
|
||||
|
||||
|
||||
def _records(root):
|
||||
for tid in refresh.trail_ids(root):
|
||||
yield tid, refresh.load_toml(os.path.join(root, tid, "trail.toml"))
|
||||
|
||||
|
||||
def missing_ids(root):
|
||||
"""Ids of the records with no hike.season, sorted."""
|
||||
return sorted(tid for tid, rec in _records(root) if not (rec.get("hike") or {}).get("season"))
|
||||
|
||||
|
||||
def batches(root, size=10):
|
||||
by_group = {}
|
||||
for tid, rec in _records(root):
|
||||
if not (rec.get("hike") or {}).get("season"):
|
||||
by_group.setdefault(group_of(rec), []).append(tid)
|
||||
chunks = []
|
||||
for name in list(REGION_GROUPS) + [OTHER]:
|
||||
ids = sorted(by_group.get(name, []))
|
||||
chunks += [ids[i:i + size] for i in range(0, len(ids), size)]
|
||||
out = []
|
||||
carry = None # a small chunk waiting for the next one to absorb it
|
||||
for chunk in chunks:
|
||||
if carry is not None:
|
||||
if len(carry) + len(chunk) <= size:
|
||||
chunk = carry + chunk
|
||||
else:
|
||||
out.append(carry)
|
||||
carry = None
|
||||
if len(chunk) < MIN_BATCH:
|
||||
if out and len(out[-1]) + len(chunk) <= size:
|
||||
out[-1] = out[-1] + chunk
|
||||
else:
|
||||
carry = chunk
|
||||
else:
|
||||
out.append(chunk)
|
||||
if carry is not None:
|
||||
out.append(carry)
|
||||
return out
|
||||
|
||||
|
||||
def write_batches(root, size, given_dir=None):
|
||||
staging = refresh.staging_dir(root, given_dir, create=True)
|
||||
d = os.path.join(staging, "season", "batches")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
for name in os.listdir(d):
|
||||
if name.startswith("season-") and name.endswith(".txt"):
|
||||
os.remove(os.path.join(d, name))
|
||||
got = batches(root, size)
|
||||
for n, ids in enumerate(got, 1):
|
||||
with open(os.path.join(d, f"season-{n:02d}.txt"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(ids) + "\n")
|
||||
return d, got
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--n", type=int, default=10, help="trails per batch")
|
||||
parser.add_argument("--dir", default=None, help="staging directory")
|
||||
args = parser.parse_args(argv)
|
||||
d, got = write_batches(os.path.dirname(HERE), args.n, args.dir)
|
||||
print(f"{len(got)} batches, {sum(len(b) for b in got)} trails, written to {d}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Propose a season_basis for every record that already has a season.
|
||||
|
||||
Python 3 standard library only. Run from the repository root:
|
||||
|
||||
python3 tools/season_classify.py table [--dir DIR]
|
||||
python3 tools/season_classify.py proposals --reviewed PATH [--dir DIR]
|
||||
|
||||
The suggestion is a starting point for a person's review, never written to a
|
||||
record by this tool. See docs/superpowers/plans/2026-11-20-season-on-every-trail.md.
|
||||
"""
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime
|
||||
import os
|
||||
from urllib.parse import urlparse
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import refresh # noqa: E402
|
||||
|
||||
COLUMNS = ("id", "season", "months", "publishers", "urls",
|
||||
"n_sources", "n_publishers", "suggested", "reason")
|
||||
|
||||
|
||||
def _host(url):
|
||||
if not isinstance(url, str) or not url:
|
||||
return ""
|
||||
host = urlparse(url).hostname or ""
|
||||
host = host.lower()
|
||||
return host[4:] if host.startswith("www.") else host
|
||||
|
||||
|
||||
def _naming_sources(rec):
|
||||
sources = (rec.get("hike") or {}).get("source") or []
|
||||
return [s for s in sources if isinstance(s, dict) and "season" in (s.get("facts") or [])]
|
||||
|
||||
|
||||
def _primary_signals(rec):
|
||||
"""Yield (host, reason) for each page that would make a source primary."""
|
||||
hike = rec.get("hike") or {}
|
||||
if _host(hike.get("official_url")):
|
||||
yield _host(hike["official_url"]), "source host matches hike.official_url"
|
||||
source_table = rec.get("source") or {}
|
||||
if _host(source_table.get("publisher_url")):
|
||||
yield _host(source_table["publisher_url"]), "source host matches source.publisher_url"
|
||||
if rec.get("kind") == "route":
|
||||
for guide in rec.get("guide") or []:
|
||||
if isinstance(guide, dict) and guide.get("link_is") in ("author", "publisher"):
|
||||
if _host(guide.get("url")):
|
||||
yield _host(guide["url"]), "route author guide host (route author counts as primary)"
|
||||
route = rec.get("route") or {}
|
||||
if _host(route.get("creator_words_url")):
|
||||
yield _host(route["creator_words_url"]), \
|
||||
"route author creator_words_url host (route author counts as primary)"
|
||||
|
||||
|
||||
def suggest_basis(rec):
|
||||
"""Return (basis, reason) for a record that has a season."""
|
||||
naming = _naming_sources(rec)
|
||||
naming_hosts = {_host(s.get("url")) for s in naming} - {""}
|
||||
for host, reason in _primary_signals(rec):
|
||||
if host in naming_hosts:
|
||||
return "primary", reason
|
||||
publishers = {str(s.get("publisher", "")).strip().casefold()
|
||||
for s in naming if str(s.get("publisher", "")).strip()}
|
||||
if len(publishers) >= 2:
|
||||
return "sources", f"{len(publishers)} different publishers name season, none primary"
|
||||
if naming:
|
||||
return "source", "one non-primary publisher names season"
|
||||
return "source", "no source names season"
|
||||
|
||||
|
||||
def table(root):
|
||||
rows = []
|
||||
for tid in refresh.trail_ids(root):
|
||||
rec = refresh.load_toml(os.path.join(root, tid, "trail.toml"))
|
||||
hike = rec.get("hike") or {}
|
||||
if not hike.get("season"):
|
||||
continue
|
||||
naming = _naming_sources(rec)
|
||||
publishers = [str(s.get("publisher", "")) for s in naming]
|
||||
distinct = {p.strip().casefold() for p in publishers if p.strip()}
|
||||
suggested, reason = suggest_basis(rec)
|
||||
rows.append({
|
||||
"id": tid,
|
||||
"season": hike["season"],
|
||||
"months": hike.get("months"),
|
||||
"publishers": publishers,
|
||||
"urls": [s.get("url", "") for s in naming],
|
||||
"n_sources": len(naming),
|
||||
"n_publishers": len(distinct),
|
||||
"suggested": suggested,
|
||||
"reason": reason,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def _cell(value):
|
||||
if isinstance(value, list):
|
||||
return "; ".join(str(v) for v in value)
|
||||
return value
|
||||
|
||||
|
||||
def write_table(root, given_dir=None):
|
||||
staging = refresh.staging_dir(root, given_dir, create=True)
|
||||
out_dir = os.path.join(staging, "season")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
path = os.path.join(out_dir, "classification.csv")
|
||||
rows = table(root)
|
||||
with open(path, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerow(COLUMNS)
|
||||
for row in rows:
|
||||
writer.writerow([_cell(row[c]) for c in COLUMNS])
|
||||
return path, len(rows)
|
||||
|
||||
|
||||
BASIS_WORDS = {
|
||||
"primary": "the page of the body that manages the trail or, for a route, its author",
|
||||
"sources": "two or more pages from different publishers that agree",
|
||||
"source": "one page that is not the trail's own",
|
||||
}
|
||||
|
||||
|
||||
def read_reviewed(path):
|
||||
"""The reviewed file: {id: basis}. Only the three sourced bases are allowed."""
|
||||
out = {}
|
||||
with open(path, newline="", encoding="utf-8") as f:
|
||||
for row in csv.DictReader(f):
|
||||
tid, basis = (row.get("id") or "").strip(), (row.get("basis") or "").strip()
|
||||
if basis not in BASIS_WORDS:
|
||||
raise ValueError(f"{tid}: basis {basis!r} must be one of {', '.join(BASIS_WORDS)}")
|
||||
out[tid] = basis
|
||||
return out
|
||||
|
||||
|
||||
def _toml_str(text):
|
||||
return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
def proposals(root, reviewed_csv, given_dir=None):
|
||||
"""Stage one change proposal per reviewed row; return how many."""
|
||||
bases = read_reviewed(reviewed_csv)
|
||||
staging = refresh.staging_dir(root, given_dir, create=True)
|
||||
out = os.path.join(staging, "staged", "season-classify")
|
||||
today = datetime.date.today().isoformat()
|
||||
report = []
|
||||
for tid in refresh.trail_ids(root):
|
||||
if tid not in bases:
|
||||
continue
|
||||
rec = refresh.load_toml(os.path.join(root, tid, "trail.toml"))
|
||||
hike = rec.get("hike") or {}
|
||||
naming = _naming_sources(rec)
|
||||
if not hike.get("season") or not naming:
|
||||
raise ValueError(f"{tid}: no season or no source naming it")
|
||||
src = naming[0]
|
||||
basis = bases[tid]
|
||||
publishers = "; ".join(sorted({str(s.get("publisher", "")).strip()
|
||||
for s in naming if str(s.get("publisher", "")).strip()}))
|
||||
lines = [
|
||||
"[[proposal]]", 'kind = "change"', f"id = {_toml_str(tid)}", f"date = {_toml_str(today)}",
|
||||
f"summary = {_toml_str('Record where the season came from.')}", "",
|
||||
"[[proposal.edit]]", 'field = "hike.season_basis"', f"new = {_toml_str(basis)}",
|
||||
f"page = {_toml_str(src['url'])}", f"quote = {_toml_str(hike['season'])}", "",
|
||||
"[proposal.history]",
|
||||
f"change = {_toml_str('The season is recorded as coming from ' + BASIS_WORDS[basis] + '.')}",
|
||||
f"basis = {_toml_str('The season is stated by ' + publishers + ' as: ' + hike['season'] + '.')}",
|
||||
f"basis_url = {_toml_str(src['url'])}",
|
||||
'asked_by = "the dataset\'s own check"', 'fields = ["hike.season_basis"]', "",
|
||||
]
|
||||
d = os.path.join(out, tid)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
with open(os.path.join(d, "proposal.toml"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines))
|
||||
report.append((tid, "changed", src["url"], f"season_basis {basis}"))
|
||||
with open(os.path.join(out, "report.csv"), "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["id", "outcome", "pages", "remark"])
|
||||
w.writerows(report)
|
||||
return len(report)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
p_table = sub.add_parser("table", help="write the classification table")
|
||||
p_table.add_argument("--dir", default=None, help="staging directory")
|
||||
p_prop = sub.add_parser("proposals", help="stage a proposal per reviewed row")
|
||||
p_prop.add_argument("--reviewed", required=True)
|
||||
p_prop.add_argument("--dir", default=None, help="staging directory")
|
||||
args = parser.parse_args(argv)
|
||||
root = os.path.dirname(HERE)
|
||||
if args.cmd == "proposals":
|
||||
print(f"{proposals(root, args.reviewed, args.dir)} proposals staged")
|
||||
return 0
|
||||
if args.cmd == "table":
|
||||
path, n = write_table(root, args.dir)
|
||||
print(f"{n} rows written to {path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Tests for tools/season.py check_season.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import season # noqa: E402
|
||||
import validate as V # noqa: E402
|
||||
import refresh # noqa: E402
|
||||
|
||||
|
||||
def src(publisher, facts=("season", "months"), url="https://example.org/trail"):
|
||||
return {"url": url, "publisher": publisher, "facts": list(facts)}
|
||||
|
||||
|
||||
def check(**fields):
|
||||
hike = {
|
||||
"season": "June to September",
|
||||
"months": [6, 7, 8, 9],
|
||||
"season_basis": "primary",
|
||||
"source": [src("Park Service")],
|
||||
}
|
||||
for k, v in fields.items():
|
||||
if v is None:
|
||||
hike.pop(k, None)
|
||||
else:
|
||||
hike[k] = v
|
||||
errors = []
|
||||
season.check_season("t", hike, errors)
|
||||
return errors
|
||||
|
||||
|
||||
class SeasonBasisTest(unittest.TestCase):
|
||||
def test_primary_with_one_naming_source_passes(self):
|
||||
self.assertEqual(check(), [])
|
||||
|
||||
def test_season_without_basis_is_an_error(self):
|
||||
errors = check(season_basis=None)
|
||||
self.assertTrue(any("season_basis" in e for e in errors), errors)
|
||||
|
||||
def test_basis_without_season_is_an_error(self):
|
||||
errors = check(season=None, months=None)
|
||||
self.assertTrue(any("season_basis" in e for e in errors), errors)
|
||||
|
||||
def test_unknown_basis_is_an_error(self):
|
||||
errors = check(season_basis="guessed")
|
||||
self.assertTrue(any("season_basis" in e for e in errors), errors)
|
||||
|
||||
def test_months_without_season_is_an_error(self):
|
||||
errors = check(season=None, season_basis=None)
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_season_without_months_is_an_error(self):
|
||||
errors = check(months=None)
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_sources_needs_two_publishers(self):
|
||||
same = [src("Guide A", url="https://a.example/1"), src("guide a", url="https://a.example/2")]
|
||||
errors = check(season_basis="sources", source=same)
|
||||
self.assertEqual(len(errors), 1, errors)
|
||||
diff = [src("Guide A", url="https://a.example/1"), src("Guide B", url="https://b.example/1")]
|
||||
self.assertEqual(check(season_basis="sources", source=diff), [])
|
||||
|
||||
def test_source_basis_needs_a_naming_source(self):
|
||||
self.assertEqual(check(season_basis="source"), [])
|
||||
errors = check(season_basis="source", source=[src("Guide A", facts=("days",))])
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_source_basis_needs_exactly_one_publisher(self):
|
||||
two = [src("Park Service"), src("Blog", url="https://example.org/b")]
|
||||
errors = check(season_basis="source", source=two)
|
||||
self.assertTrue(any("exactly one publisher" in e for e in errors), errors)
|
||||
same = [src("Park Service"), src("Park Service", url="https://example.org/b")]
|
||||
self.assertEqual(check(season_basis="source", source=same), [])
|
||||
|
||||
def test_primary_needs_a_naming_source(self):
|
||||
errors = check(source=[src("Park Service", facts=("days",))])
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_estimate_needs_a_method_and_refuses_one_otherwise(self):
|
||||
self.assertTrue(check(season_basis="estimate"))
|
||||
self.assertEqual(
|
||||
check(season_basis="estimate", season_method="Estimated from climate normals."), [])
|
||||
self.assertTrue(check(season_basis="estimate", season_method=""))
|
||||
self.assertTrue(check(season_basis="estimate", season_method="x" * 401))
|
||||
self.assertTrue(check(season_method="Estimated from climate normals."))
|
||||
|
||||
def test_estimate_with_two_naming_sources_is_an_error(self):
|
||||
two = [src("Climate", url="https://c.example/1"), src("Other", url="https://o.example/1")]
|
||||
errors = check(season_basis="estimate", season_method="Estimated from climate.", source=two)
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_estimate_with_no_naming_source_is_an_error(self):
|
||||
errors = check(season_basis="estimate", season_method="Estimated from climate.",
|
||||
source=[src("Climate", facts=("days",))])
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_a_hike_without_season_passes_until_required(self):
|
||||
self.assertEqual(check(season=None, months=None, season_basis=None, source=None), [])
|
||||
|
||||
def test_required_flag_makes_it_an_error(self):
|
||||
with mock.patch.object(season, "SEASON_REQUIRED", True):
|
||||
errors = check(season=None, months=None, season_basis=None, source=None)
|
||||
self.assertTrue(any("season" in e for e in errors), errors)
|
||||
|
||||
def test_method_without_season_is_an_error(self):
|
||||
errors = check(season=None, months=None, season_basis=None, season_method="Some method.")
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_every_record_with_a_season_passes_the_validator(self):
|
||||
errors = []
|
||||
for tid in refresh.trail_ids(V.ROOT):
|
||||
rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
|
||||
if (rec.get("hike") or {}).get("season"):
|
||||
V.check_hike(tid, rec, errors)
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
def test_provenance_keys_need_no_source_fact(self):
|
||||
hike = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "primary",
|
||||
"source": [src("Park Service", facts=("season", "months"))]}
|
||||
errors = []
|
||||
V.check_hike("t", {"hike": hike}, errors)
|
||||
self.assertFalse([e for e in errors if "not named in the facts" in e], errors)
|
||||
self.assertFalse([e for e in errors if "not a known field" in e], errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Tests for tools/season_batches.py and the researchers' brief.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests -p "test_season_batches.py"
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import refresh # noqa: E402
|
||||
import season_batches as B # noqa: E402
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def write(root, tid, regions, season=None):
|
||||
os.makedirs(os.path.join(root, tid))
|
||||
hike = '[hike]\nshape = "loop"\n' + (f'season = "{season}"\nmonths = [6, 7]\n' if season else "")
|
||||
with open(os.path.join(root, tid, "trail.toml"), "w", encoding="utf-8") as f:
|
||||
f.write(f'name = "{tid}"\ncountry = "US"\nregions = {regions!r}\n\n'.replace("'", '"') + hike)
|
||||
|
||||
|
||||
class BatchesTest(unittest.TestCase):
|
||||
def test_missing_ids_are_the_records_without_a_season(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
write(root, "b-trail", ["CA"], season="June to July")
|
||||
write(root, "c-trail", ["CA"])
|
||||
write(root, "a-trail", ["WY"])
|
||||
self.assertEqual(B.missing_ids(root), ["a-trail", "c-trail"])
|
||||
|
||||
def test_batches_are_at_most_the_size_and_cover_every_id_once(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
for i in range(23):
|
||||
write(root, f"ca-{i:02d}", ["CA"])
|
||||
for i in range(7):
|
||||
write(root, f"pa-{i:02d}", ["PA"])
|
||||
got = B.batches(root, 10)
|
||||
flat = [x for b in got for x in b]
|
||||
self.assertEqual(sorted(flat), B.missing_ids(root))
|
||||
self.assertEqual(len(flat), len(set(flat)))
|
||||
self.assertTrue(all(0 < len(b) <= 10 for b in got))
|
||||
|
||||
def test_a_batch_stays_in_one_region_group_unless_joined(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
for i in range(23):
|
||||
write(root, f"ca-{i:02d}", ["CA"])
|
||||
for i in range(3):
|
||||
write(root, f"pa-{i:02d}", ["PA"])
|
||||
got = B.batches(root, 10)
|
||||
west = [b for b in got if all(x.startswith("ca-") for x in b)]
|
||||
self.assertEqual([len(b) for b in west], [10, 10])
|
||||
# the leftover 3 and the 3 Pennsylvania trails are each fewer than 5, so they share a batch
|
||||
mixed = [b for b in got if b not in west]
|
||||
self.assertEqual([len(b) for b in mixed], [6])
|
||||
|
||||
def test_a_small_leftover_joins_a_neighbour_with_room(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
for i in range(12):
|
||||
write(root, f"ca-{i:02d}", ["CA"]) # 10 and 2
|
||||
for i in range(4):
|
||||
write(root, f"or-{i:02d}", ["OR"]) # same group as CA
|
||||
got = B.batches(root, 10)
|
||||
self.assertEqual(sorted(len(b) for b in got), [6, 10])
|
||||
|
||||
def test_real_count(self):
|
||||
n = len(B.missing_ids(ROOT))
|
||||
recs = [t for t in refresh.trail_ids(ROOT)
|
||||
if not (refresh.load_toml(os.path.join(ROOT, t, "trail.toml")).get("hike") or {}).get("season")]
|
||||
self.assertEqual(n, len(recs))
|
||||
got = B.batches(ROOT)
|
||||
# each region group can leave one part-full batch
|
||||
self.assertGreaterEqual(len(got), math.ceil(n / 10))
|
||||
self.assertLessEqual(len(got), math.ceil(n / 10) + len(B.REGION_GROUPS))
|
||||
self.assertEqual(sorted(x for b in got for x in b), B.missing_ids(ROOT))
|
||||
|
||||
def test_every_region_code_in_the_records_has_a_group(self):
|
||||
for tid in refresh.trail_ids(ROOT):
|
||||
rec = refresh.load_toml(os.path.join(ROOT, tid, "trail.toml"))
|
||||
self.assertNotEqual(B.group_of(rec), B.OTHER, tid)
|
||||
|
||||
def test_the_brief_names_what_a_researcher_records(self):
|
||||
text = open(os.path.join(ROOT, "docs", "season-research.md"), encoding="utf-8").read()
|
||||
for want in ("hike.season_basis", "hike.months", "quote", "not-found", "publisher"):
|
||||
self.assertIn(want, text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Tests for tools/season_classify.py.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import csv
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import refresh # noqa: E402
|
||||
import season # noqa: E402
|
||||
import season_classify as C # noqa: E402
|
||||
import validate as V # noqa: E402
|
||||
import test_refresh as TR # noqa: E402
|
||||
|
||||
|
||||
def rec(**kw):
|
||||
base = {
|
||||
"hike": {
|
||||
"season": "June to September",
|
||||
"months": [6, 7, 8, 9],
|
||||
"source": [{"url": "https://www.example.org/trail",
|
||||
"publisher": "Example Publisher",
|
||||
"facts": ["season", "months"]}],
|
||||
}
|
||||
}
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
|
||||
class SuggestBasisTest(unittest.TestCase):
|
||||
def test_official_site_host_is_primary(self):
|
||||
r = rec()
|
||||
r["hike"]["official_url"] = "https://example.org/trail-page"
|
||||
basis, reason = C.suggest_basis(r)
|
||||
self.assertEqual(basis, "primary")
|
||||
self.assertIn("official_url", reason)
|
||||
|
||||
def test_source_publisher_host_is_primary(self):
|
||||
r = rec(source={"publisher": "X", "publisher_url": "https://www.example.org/"})
|
||||
basis, reason = C.suggest_basis(r)
|
||||
self.assertEqual(basis, "primary")
|
||||
self.assertIn("publisher_url", reason)
|
||||
|
||||
def test_route_author_page_is_primary(self):
|
||||
r = rec(kind="route", route={"creator": "A Hiker"},
|
||||
guide=[{"title": "G", "url": "https://example.org/guide", "link_is": "author"}])
|
||||
basis, reason = C.suggest_basis(r)
|
||||
self.assertEqual(basis, "primary")
|
||||
self.assertIn("route author", reason)
|
||||
|
||||
def test_route_creator_words_host_is_primary(self):
|
||||
r = rec(kind="route", route={"creator": "A Hiker",
|
||||
"creator_words_url": "https://example.org/words"})
|
||||
basis, _ = C.suggest_basis(r)
|
||||
self.assertEqual(basis, "primary")
|
||||
|
||||
def test_two_unrelated_publishers_are_sources(self):
|
||||
r = rec()
|
||||
r["hike"]["source"] = [
|
||||
{"url": "https://a.example/t", "publisher": "Guide A", "facts": ["season"]},
|
||||
{"url": "https://b.example/t", "publisher": "Guide B", "facts": ["season", "months"]},
|
||||
]
|
||||
basis, reason = C.suggest_basis(r)
|
||||
self.assertEqual(basis, "sources")
|
||||
self.assertTrue(reason)
|
||||
|
||||
def test_one_unrelated_page_is_source(self):
|
||||
basis, reason = C.suggest_basis(rec())
|
||||
self.assertEqual(basis, "source")
|
||||
self.assertTrue(reason)
|
||||
|
||||
def test_www_and_bare_host_are_the_same_host(self):
|
||||
r = rec()
|
||||
r["hike"]["official_url"] = "https://example.org/x"
|
||||
r["hike"]["source"][0]["url"] = "https://www.example.org/y"
|
||||
self.assertEqual(C.suggest_basis(r)[0], "primary")
|
||||
|
||||
def test_non_route_guide_host_is_not_primary(self):
|
||||
r = rec(guide=[{"title": "G", "url": "https://example.org/guide", "link_is": "author"}])
|
||||
self.assertEqual(C.suggest_basis(r)[0], "source")
|
||||
|
||||
|
||||
class TableTest(unittest.TestCase):
|
||||
def test_table_covers_every_record_with_a_season(self):
|
||||
rows = C.table(V.ROOT)
|
||||
expected = 0
|
||||
for tid in refresh.trail_ids(V.ROOT):
|
||||
r = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
|
||||
if (r.get("hike") or {}).get("season"):
|
||||
expected += 1
|
||||
self.assertEqual(expected, 109)
|
||||
self.assertEqual(len(rows), expected)
|
||||
for row in rows:
|
||||
self.assertIn(row["suggested"], season.BASES)
|
||||
|
||||
def test_table_has_a_reason_for_every_row(self):
|
||||
for row in C.table(V.ROOT):
|
||||
self.assertTrue(row["reason"], row["id"])
|
||||
self.assertTrue(row["season"], row["id"])
|
||||
|
||||
|
||||
class ProposalsTest(unittest.TestCase):
|
||||
def test_a_proposal_collects_cleanly_and_applies(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = TR.make_repo(tmp)
|
||||
path = os.path.join(root, "aaa", "trail.toml")
|
||||
text = TR.read(root, "aaa/trail.toml")
|
||||
text = text.replace('official_url = "https://example.org/aaa/"\n',
|
||||
'official_url = "https://example.org/aaa/"\n'
|
||||
'season = "June to September"\nmonths = [6, 7, 8, 9]\n', 1)
|
||||
text += ('\n[[hike.source]]\nurl = "https://example.org/aaa/season"\n'
|
||||
'publisher = "Example Club"\nfacts = ["season", "months"]\n')
|
||||
TR.write(path, text)
|
||||
d = os.path.join(tmp, "stage")
|
||||
os.makedirs(os.path.join(d, "season"))
|
||||
reviewed = os.path.join(d, "season", "classification.reviewed.csv")
|
||||
with open(reviewed, "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["id", "basis", "note"])
|
||||
w.writerow(["aaa", "primary", ""])
|
||||
self.assertEqual(C.proposals(root, reviewed, d), 1)
|
||||
code, out = TR.main(root, "--dir", d, "collect")
|
||||
self.assertEqual(code, 0, out)
|
||||
coll = refresh.load_toml(os.path.join(d, "collected.toml"))
|
||||
props = coll["proposal"]
|
||||
self.assertEqual(len(props), 1)
|
||||
self.assertEqual(props[0]["status"], "proposed", out)
|
||||
with open(os.path.join(d, "owner.csv"), "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["pid", "digest", "decision", "note"])
|
||||
w.writerow([props[0]["pid"], props[0]["digest"], "accept", ""])
|
||||
code, out = TR.main(root, "--dir", d, "collect")
|
||||
self.assertEqual(code, 0, out)
|
||||
code, out = TR.main(root, "--dir", d, "apply")
|
||||
self.assertEqual(code, 0, out)
|
||||
rec_after = refresh.load_toml(path)
|
||||
self.assertEqual(rec_after["hike"]["season_basis"], "primary")
|
||||
last = rec_after["history"][-1]
|
||||
self.assertEqual(last["fields"], ["hike.season_basis"])
|
||||
|
||||
def test_reviewed_rows_must_name_a_known_basis(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
reviewed = os.path.join(tmp, "r.csv")
|
||||
with open(reviewed, "w", newline="", encoding="utf-8") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["id", "basis"])
|
||||
w.writerow(["aaa", "estimate"])
|
||||
with self.assertRaises(ValueError):
|
||||
C.read_reviewed(reviewed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Tests that season_basis and season_method are known fields and documented.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import trail_history as H # noqa: E402
|
||||
import validate as V # noqa: E402
|
||||
|
||||
|
||||
class SeasonFieldsTest(unittest.TestCase):
|
||||
def test_the_new_fields_are_known_to_the_history_tool(self):
|
||||
for f in ("hike.season_basis", "hike.season_method"):
|
||||
self.assertIn(f, H.SCHEMA_FIELDS)
|
||||
self.assertTrue(H.is_fact(f))
|
||||
|
||||
def test_the_facts_text_names_them(self):
|
||||
self.assertIn("season_basis", H.FACTS_TEXT)
|
||||
|
||||
def test_the_schema_documents_them_and_the_estimate_exception(self):
|
||||
text = open(os.path.join(V.ROOT, "docs", "schema.md"), encoding="utf-8").read()
|
||||
for needle in ("`season_basis`", "`season_method`", "except season, which may be estimated"):
|
||||
self.assertIn(needle, text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -29,7 +29,7 @@ _TABLES = {
|
||||
"shield": ("status", "logo_source", "contact", "note", "logo_file", "logo_owner"),
|
||||
"verification": ("verified", "date", "measured_km", "difference_percent", "parts", "note"),
|
||||
"hike": ("summary", "official_url", "start", "end", "start_lonlat", "end_lonlat", "shape",
|
||||
"days", "season", "months", "high_point", "high_point_m", "terrain", "travel",
|
||||
"days", "season", "months", "season_basis", "season_method", "high_point", "high_point_m", "terrain", "travel",
|
||||
"permit", "unfinished", "caution", "checked"),
|
||||
"hike.source": ("url", "publisher", "facts"),
|
||||
"route": ("creator", "year", "line_policy", "creator_words", "creator_words_url",
|
||||
@@ -69,7 +69,7 @@ FACTS_TEXT = (
|
||||
"designation, inclusion; source.* (status, publisher, publisher_url, url, licence, licence_text, "
|
||||
"permission_*, attribution, osm_only, line_source, line_file, line_absent_reason, "
|
||||
"decision, decision_text, redistributable); osm.relation; shield.* except note; "
|
||||
"hike.* except summary, checked and source (start, end, official_url, days, season, terrain, "
|
||||
"hike.* except summary, checked and source (start, end, official_url, days, season, months, season_basis, season_method, terrain, "
|
||||
"travel, high_point, permit, unfinished, caution and the rest); route.* except note; "
|
||||
"guide.* except price; place.* except km (kind, slug, basis, source). "
|
||||
"A replaced track file counts as a change to source.line_file."
|
||||
|
||||
+8
-2
@@ -17,6 +17,11 @@ import os
|
||||
import re
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"season", os.path.join(ROOT, "tools", "season.py"))
|
||||
season = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(season)
|
||||
MAX_BYTES = 50 * 1024 * 1024
|
||||
ALLOWED_LICENCES = {
|
||||
"us-gov-public-domain", "CC-BY-4.0", "CC-BY", "ODbL-1.0", "stated-permission",
|
||||
@@ -34,7 +39,7 @@ HIKE_FACTS = {"summary", "official_url", "start", "end", "shape", "days", "seaso
|
||||
"months", "travel", "start_lonlat", "end_lonlat"}
|
||||
LONLAT_BOUNDS = (-180.0, -50.0, 24.0, 75.0) # lon min, lon max, lat min, lat max
|
||||
HIKE_TRAVEL = {"trail", "trail-and-road", "some-cross-country", "mostly-cross-country"}
|
||||
HIKE_KEYS = HIKE_FACTS | {"checked"}
|
||||
HIKE_KEYS = HIKE_FACTS | {"checked"} | season.PROVENANCE_KEYS
|
||||
ELEVATION_KEYS = {"highest", "lowest", "ascent_m", "descent_m", "track_km", "published_km",
|
||||
"coverage", "parts", "orientation", "profile", "part_starts_km", "source"}
|
||||
ELEVATION_REQUIRED = ELEVATION_KEYS - {"part_starts_km"}
|
||||
@@ -371,9 +376,10 @@ def check_hike(tid, rec, errors):
|
||||
covered.update(("high_point", "high_point_m"))
|
||||
else:
|
||||
covered.add(fact)
|
||||
for name in sorted(set(hike) & HIKE_KEYS - {"checked"}) if sources else []:
|
||||
for name in sorted(set(hike) & HIKE_KEYS - {"checked"} - season.PROVENANCE_KEYS) if sources else []:
|
||||
if name not in covered:
|
||||
errors.append(f"{tid}: hike.{name} is not named in the facts of any hike source")
|
||||
season.check_season(tid, hike, errors)
|
||||
|
||||
|
||||
def check_elevation(tid, tdir, rec, errors):
|
||||
|
||||
Reference in new issue
Block a user