Record where each of the 109 seasons came from

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 09:45:32 -07:00
1 parent ea6a7d175f
commit fbb43d9ff0
111 files changed
+1219

No files matched your search

+73
View File
@@ -4,6 +4,7 @@
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.
@@ -14,6 +15,7 @@ sys.dont_write_bytecode = True
import argparse
import csv
import datetime
import os
from urllib.parse import urlparse
@@ -119,13 +121,84 @@ def write_table(root, given_dir=None):
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}")
+56
View File
@@ -3,8 +3,11 @@
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
@@ -14,6 +17,7 @@ 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):
@@ -102,5 +106,57 @@ class TableTest(unittest.TestCase):
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()