Add the season classification table
This commit is contained in:
1 parent
e08aaa192b
commit
ea6a7d175f
2 files changed
+242
No files matched your search
@@ -0,0 +1,136 @@
|
||||
#!/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]
|
||||
|
||||
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 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)
|
||||
|
||||
|
||||
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")
|
||||
args = parser.parse_args(argv)
|
||||
root = os.path.dirname(HERE)
|
||||
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,106 @@
|
||||
"""Tests for tools/season_classify.py.
|
||||
|
||||
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 refresh # noqa: E402
|
||||
import season # noqa: E402
|
||||
import season_classify as C # noqa: E402
|
||||
import validate as V # 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"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user