Files
longhikes/web/tools/make_thumbs.py
T
swaitsandClaude Fable 5.2 f2d3b71810
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s
Add 130 views of the same records, speed up map pages, and say who maintains the site
- New pages built from the records: lists by length, time to walk,
  month, kind of walking and holder; place-by-list pages; a Triple Crown
  table and key-figure tables for the National Scenic and Recreation
  Trails; highest points, most climbing and climb per mile; a page for
  every route author, with the authors of three or more routes leading
  the authors page; connected trails; recently added and changed; a
  glossary and a method page. Every place page opens with a summary.
- Trail pages open with an "In brief" paragraph generated from the
  record and show when the record was last checked. The About page says
  who maintains the site and how to reach them.
- The map starts when it is reached, not with the page. The site's own
  CSS, scripts and fonts are fingerprinted and cached for a year. Every
  image has its dimensions.
- Titles are held to 60 characters and share previews get their own
  shorter description.
- Social cards are redrawn so a long name can no longer push text into
  the footer, and the site-wide card takes its wording from the site
  settings instead of an old hand-made image.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 16:51:13 -07:00

98 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""Make the small PNG logo thumbnails the site shows in lists.
For every <id>/shield.png (or, where there is no PNG, <id>/shield.svg) in the
repository root, writes web/thumbs/<id>.png, scaled to fit within 256 x 256 px
(a PNG is never enlarged; an SVG is drawn at that size, so a thumbnail is never
blurred), metadata stripped and transparency kept. A vector logo can weigh
hundreds of kilobytes (the Bartram Trail's is 345 KB); its thumbnail a few tens. Needs ImageMagick 7 (`magick`) on the PATH; runs optipng
too when it is installed. Run on a developer machine and commit the output:
the site build itself is standard library only and does not run this.
python3 web/tools/make_thumbs.py [--force]
A thumbnail newer than its source is left alone unless --force is given.
Thumbnails whose source no longer exists are removed.
"""
import argparse
import os
import shutil
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
THUMBS = os.path.join(os.path.dirname(HERE), "thumbs")
MAX_SIDE = 256
def sources():
"""{id: path} for each <id>/shield.png, or <id>/shield.svg when there is no PNG,
directly under the repository root."""
found = {}
for name in sorted(os.listdir(ROOT)):
if name.startswith((".", "_")):
continue
for ext in ("png", "svg"):
path = os.path.join(ROOT, name, f"shield.{ext}")
if os.path.isfile(path):
found[name] = path
break
return found
def make_thumb(src, dst):
"""Write one thumbnail with ImageMagick, then optimise it when optipng is present."""
if src.endswith(".svg"):
# Drawn at 384 dpi (so the drawing is larger than the thumbnail), then fitted.
cmd = ["magick", "-background", "none", "-density", "384", src, "-strip",
"-resize", f"{MAX_SIDE}x{MAX_SIDE}>", "PNG32:" + dst]
else:
cmd = ["magick", src, "-strip", "-resize", f"{MAX_SIDE}x{MAX_SIDE}>", "PNG32:" + dst]
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
if os.path.exists(dst):
os.remove(dst)
sys.exit(f"make_thumbs: magick failed on {os.path.relpath(src, ROOT)}: "
f"{e.stderr.decode(errors='replace').strip()}")
if shutil.which("optipng"):
subprocess.run(["optipng", "-quiet", "-o2", dst], check=True)
def main(argv=None):
ap = argparse.ArgumentParser(description="Make web/thumbs/<id>.png from each <id>/shield.png (or .svg).")
ap.add_argument("--force", action="store_true", help="rebuild thumbnails that are up to date")
args = ap.parse_args(argv)
if shutil.which("magick") is None:
sys.exit("make_thumbs: 'magick' (ImageMagick 7) was not found on the PATH; install ImageMagick and retry")
os.makedirs(THUMBS, exist_ok=True)
srcs = sources()
written = skipped = removed = 0
total = 0
for tid, src in srcs.items():
dst = os.path.join(THUMBS, f"{tid}.png")
if not args.force and os.path.isfile(dst) and os.path.getmtime(dst) >= os.path.getmtime(src):
skipped += 1
continue
make_thumb(src, dst)
size = os.path.getsize(dst)
total += size
written += 1
print(f"wrote {os.path.relpath(dst, ROOT)} ({size} bytes)")
for name in sorted(os.listdir(THUMBS)):
if name.endswith(".png") and name[:-4] not in srcs:
os.remove(os.path.join(THUMBS, name))
removed += 1
print(f"removed {os.path.relpath(os.path.join(THUMBS, name), ROOT)} (no source)")
print(f"total: {written} written ({total} bytes), {skipped} up to date, {removed} removed")
return 0
if __name__ == "__main__":
sys.exit(main())