sauna-woods / validate.py
divelux's picture
Version 1.0
b74d26f verified
Raw History Blame Contribute Delete
8.26 kB
#!/usr/bin/env python3
"""Validate Sauna Woods. Exit code 0 = all checks pass. Standard library only.
Checks: columns and order, required fields, unique woods, controlled vocabularies,
density types and ranges (min <= typical <= max), lb/ft3 equal to the kg/m3 value
converted, a density basis and source wherever there is a density (and none where
there is not), a sauna-use source for every row, address format, tidy text,
CSV/JSON agreement, the counts quoted in README.md, and banned wording.
This script works offline. It checks the structure of the files; it does not re-read
the source pages.
"""
import csv
import json
import os
import re
import sys
import unicodedata
HERE = os.path.dirname(os.path.abspath(__file__))
LB_FT3_PER_KG_M3 = 0.062428
COLUMNS = [
"wood", "latin_name", "wood_type",
"used_for_benches", "used_for_walls_ceiling", "used_for_exterior",
"density_kg_m3_min", "density_kg_m3_typical", "density_kg_m3_max",
"density_lb_ft3_min", "density_lb_ft3_typical", "density_lb_ft3_max",
"density_basis", "resin", "scent", "typical_region", "notes",
"density_source_url", "properties_source_url", "sauna_use_source_url", "sauna_use_source_url_2", "sauna_use_source_url_3",
]
WOOD_TYPES = {"softwood", "hardwood", "thermally modified softwood", "thermally modified hardwood"}
USED = {"", "yes", "no", "mixed"}
RESIN = {"", "yes", "no"}
KG = ["density_kg_m3_min", "density_kg_m3_typical", "density_kg_m3_max"]
LB = ["density_lb_ft3_min", "density_lb_ft3_typical", "density_lb_ft3_max"]
URLS = ["density_source_url", "properties_source_url", "sauna_use_source_url", "sauna_use_source_url_2", "sauna_use_source_url_3"]
# Plausible range for air-dry wood used indoors; balsa is near 150, the heaviest sauna woods are under 900.
KG_MIN, KG_MAX = 250, 950
BANNED = ["detox", "toxin", "burns fat", "burn fat", "cure", "cures", "heals", "healing", "boosts", "immune",
"hypoallergenic", "therapeutic", "antibacterial", "soak the hat", "wet the hat", "best seller", "amazon"]
errors = []
def err(msg):
errors.append(msg)
with open(os.path.join(HERE, "sauna_woods.csv"), newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
header = reader.fieldnames
rows = list(reader)
if header != COLUMNS:
err(f"columns are {header}, expected {COLUMNS}")
if not 10 <= len(rows) <= 40:
err(f"{len(rows)} rows; expected 10 to 40")
seen = set()
for i, r in enumerate(rows, start=2):
tag = f"row {i} ({r.get('wood')!r})"
for c in COLUMNS:
v = r[c]
if v != v.strip() or " " in v or "\n" in v or "\t" in v:
err(f"{tag}: untidy whitespace in {c}")
if v != unicodedata.normalize("NFC", v):
err(f"{tag}: {c} is not NFC-normalized")
for c in ("wood", "latin_name", "wood_type", "notes", "properties_source_url", "sauna_use_source_url"):
if not r[c]:
err(f"{tag}: {c} is empty")
if r["wood"].casefold() in seen:
err(f"{tag}: duplicate wood")
seen.add(r["wood"].casefold())
if r["wood_type"] not in WOOD_TYPES:
err(f"{tag}: unknown wood_type {r['wood_type']!r}")
if r["wood_type"].startswith("thermally modified") != r["wood"].startswith("Thermally modified"):
err(f"{tag}: thermally modified woods, and only those, are named 'Thermally modified ...'")
if not re.fullmatch(r"[A-Z][a-z]+ [a-z]+", r["latin_name"]):
err(f"{tag}: latin_name {r['latin_name']!r} is not a 'Genus species' binomial")
for c in ("used_for_benches", "used_for_walls_ceiling", "used_for_exterior"):
if r[c] not in USED:
err(f"{tag}: {c} must be one of {sorted(USED)}")
if not any(r[c] in ("yes", "mixed") for c in ("used_for_benches", "used_for_walls_ceiling", "used_for_exterior")):
err(f"{tag}: no confirmed sauna use at all")
if r["resin"] not in RESIN:
err(f"{tag}: resin must be one of {sorted(RESIN)}")
# density
kg = {}
for c in KG:
if r[c] == "":
continue
if not re.fullmatch(r"\d{3}", r[c]):
err(f"{tag}: {c} {r[c]!r} is not a whole number of kg/m3")
continue
kg[c] = int(r[c])
if not KG_MIN <= kg[c] <= KG_MAX:
err(f"{tag}: {c} {kg[c]} outside {KG_MIN}-{KG_MAX}")
ordered = [kg[c] for c in KG if c in kg]
if ordered != sorted(ordered):
err(f"{tag}: density must satisfy min <= typical <= max")
if ("density_kg_m3_min" in kg) != ("density_kg_m3_max" in kg):
err(f"{tag}: give both density min and max, or neither")
for ckg, clb in zip(KG, LB):
if (r[ckg] == "") != (r[clb] == ""):
err(f"{tag}: {clb} must be filled exactly when {ckg} is")
elif r[ckg] != "" and ckg in kg:
want = f"{round(kg[ckg] * LB_FT3_PER_KG_M3, 1)}"
if r[clb] != want:
err(f"{tag}: {clb} is {r[clb]}, expected {want} ({kg[ckg]} kg/m3 x {LB_FT3_PER_KG_M3})")
has_density = bool(kg)
if has_density != bool(r["density_basis"]) or has_density != bool(r["density_source_url"]):
err(f"{tag}: density_basis and density_source_url go with a density figure, and only with one")
# sources
for c in URLS:
if r[c] and not re.fullmatch(r"https://[a-z0-9.-]+\.[a-z]{2,}/\S*", r[c]):
err(f"{tag}: {c} is not an https address")
use_urls = [r[c] for c in URLS[2:] if r[c]]
if len(set(use_urls)) != len(use_urls):
err(f"{tag}: the same sauna-use source is listed twice")
if r["sauna_use_source_url_3"] and not r["sauna_use_source_url_2"] or r["sauna_use_source_url_2"] and not r["sauna_use_source_url"]:
err(f"{tag}: fill the sauna_use_source_url columns in order")
if (r["resin"] or r["scent"] or r["typical_region"]) and not r["properties_source_url"]:
err(f"{tag}: properties without a source")
for c in ("scent", "typical_region"):
if r[c].endswith("."):
err(f"{tag}: {c} should not end with a period")
if not r["notes"].endswith((".", ")")):
err(f"{tag}: notes should end with a period")
text = " ".join(r[c] for c in ("wood", "scent", "typical_region", "notes")).lower()
for b in BANNED:
if re.search(r"\b" + re.escape(b) + r"\b", text):
err(f"{tag}: banned wording {b!r}")
# CSV and JSON carry the same data (empty string in CSV = null in JSON; densities are numbers in JSON)
with open(os.path.join(HERE, "sauna_woods.json"), encoding="utf-8") as f:
data = json.load(f)
if len(data) != len(rows):
err(f"JSON has {len(data)} records, CSV has {len(rows)}")
for r, j in zip(rows, data):
if list(j) != COLUMNS:
err(f"JSON keys differ for {r['wood']!r}")
break
for c in COLUMNS:
if c in KG or c in LB:
if r[c] == "":
ok = j[c] is None
else:
ok = isinstance(j[c], (int, float)) and not isinstance(j[c], bool) and float(j[c]) == float(r[c])
if c in KG:
ok = ok and isinstance(j[c], int)
if not ok:
err(f"CSV and JSON differ at {r['wood']!r} / {c}")
elif (j[c] or "") != r[c]:
err(f"CSV and JSON differ at {r['wood']!r} / {c}")
# README numbers
readme = open(os.path.join(HERE, "README.md"), encoding="utf-8").read()
n_density = sum(1 for r in rows if any(r[c] for c in KG))
n_tm = sum(1 for r in rows if r["wood_type"].startswith("thermally modified"))
for phrase in (f"{len(rows)} woods", f"{n_density} have a density figure", f"{n_tm} are thermally modified"):
if phrase not in readme:
err(f"README.md does not say '{phrase}'")
for r in rows:
for c in URLS:
if r[c] and r[c] not in readme:
err(f"README.md does not list the source {r[c]}")
if errors:
print(f"{len(errors)} problem(s):")
for e in errors[:40]:
print(" -", e)
sys.exit(1)
by_type = {}
for r in rows:
by_type[r["wood_type"]] = by_type.get(r["wood_type"], 0) + 1
print(f"OK: {len(rows)} woods, {n_density} with a density figure, {n_tm} thermally modified, "
f"{len({u for r in rows for u in (r[c] for c in URLS) if u})} distinct source pages")
print(", ".join(f"{k} {v}" for k, v in sorted(by_type.items(), key=lambda kv: -kv[1])))