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>
This commit is contained in:
1 parent
5b80fccd1e
commit
f2d3b71810
266 files changed
+4658
-252
No files matched your search
+247
-44
@@ -4,8 +4,8 @@
|
||||
A card shows the trail's name, its length in miles and kilometres, where it is
|
||||
and, where the record has a track, the track's outline. Everything is read from
|
||||
the records and from a built site's map.json files (the track simplified to
|
||||
30 m); nothing about a trail is written here. Colours and type follow the site
|
||||
card, assets/og.png: the cream ground, the red bar, Source Serif 4 and IBM Plex
|
||||
30 m); nothing about a trail is written here. The site card, assets/og.png, is drawn here too, from the name and tagline in
|
||||
web/site.toml. Colours and type: the cream ground, the red bar, Source Serif 4 and IBM Plex
|
||||
Sans Condensed.
|
||||
|
||||
Run on a developer machine and commit the output, as web/tools/make_thumbs.py
|
||||
@@ -26,6 +26,7 @@ import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -36,7 +37,7 @@ WEB = os.path.dirname(HERE)
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import cards, records # noqa: E402
|
||||
from olt import cards, records, site as site_mod # noqa: E402
|
||||
|
||||
W, H = 1200, 630
|
||||
SCALE = 2 # drawn at twice the size, then reduced, for smooth edges
|
||||
@@ -86,15 +87,181 @@ def wrap(draw, text, fnt, width):
|
||||
return lines + [line] if line else lines
|
||||
|
||||
|
||||
def fit_title(draw, text, path, width, weight=700):
|
||||
"""The largest size (up to 84, down to 44) at which text takes three lines or fewer, and its lines."""
|
||||
for size in range(84, 43, -2):
|
||||
fnt = font(path, size, weight)
|
||||
lines = wrap(draw, text, fnt, width * SCALE)
|
||||
if len(lines) <= 3 and all(draw.textlength(x, font=fnt) <= width * SCALE for x in lines):
|
||||
return size, fnt, lines
|
||||
fnt = font(path, 44, weight)
|
||||
return 44, fnt, wrap(draw, text, fnt, width * SCALE)[:3]
|
||||
# The layout. Every element is a text line or the track, with a box in card pixels (not
|
||||
# drawn ones). The text column is one flow between the header and the footer; the name shrinks
|
||||
# until the whole block fits the safe area. draw_card() draws what layout() returns and the
|
||||
# test in web/tests/test_card_layout.py measures the same boxes, so they cannot disagree.
|
||||
HEADER_BOTTOM = 128 # the mark's lower edge
|
||||
SAFE_TOP, SAFE_BOTTOM = 152, 516 # the text column lives here: 32 px clear of the footer text
|
||||
FOOT_Y = 548 # top of the footer line (drawn with the ascender anchor)
|
||||
COL_TRACK, COL_FULL = 520, 1030 # text column width with and without a track
|
||||
TRACK_BOX = (680, 96, W - 70, 520)
|
||||
# A name too long for the column even at the smallest size gets a wider column, and the track a
|
||||
# narrower box to match: (column width, track box left edge).
|
||||
WIDER = ((590, 720), (660, 770))
|
||||
STROKE = 5
|
||||
NAME_MAX, NAME_MIN, NAME_STEP = 84, 48, 2 # name size, card px; 48 is 12 px at a 1/4 thumbnail
|
||||
NAME_LEAD = 1.1
|
||||
GAP_NAME, GAP_LENGTH = 30, 22 # ink gap name -> length, length -> places
|
||||
PLACES_LINES = 2
|
||||
|
||||
|
||||
def wrap(measure, text, width):
|
||||
"""Lines of text no wider than width, broken at spaces and after hyphens or dashes."""
|
||||
words = []
|
||||
for w in text.split():
|
||||
parts = re.split(r"(?<=[-\u2013])(?=\w)", w)
|
||||
words.append(parts)
|
||||
lines, line = [], ""
|
||||
for parts in words:
|
||||
for i, part in enumerate(parts):
|
||||
glue = " " if i == 0 else ""
|
||||
trial = f"{line}{glue}{part}" if line else part
|
||||
if measure(trial) <= width or not line:
|
||||
line = trial
|
||||
else:
|
||||
lines.append(line)
|
||||
line = part
|
||||
return lines + [line] if line else lines
|
||||
|
||||
|
||||
def wrap_name(measure, nf, name, width):
|
||||
"""A name's lines: wrapped greedily, or, for a name with a parenthetical ("Wind River High
|
||||
Route (Dixon and Wilson)"), wrapped as the name and the parenthetical on separate lines,
|
||||
whichever takes fewer lines (the second wins a tie, so the parenthetical starts a line)."""
|
||||
def fn(t):
|
||||
return measure.width(nf, t)
|
||||
plain = wrap(fn, name, width)
|
||||
if " (" not in name:
|
||||
return plain
|
||||
head, tail = name.split(" (", 1)
|
||||
split = wrap(fn, head, width) + wrap(fn, "(" + tail, width)
|
||||
return split if len(split) <= len(plain) else plain
|
||||
|
||||
|
||||
class Measure:
|
||||
"""Text measuring at the card's own pixel size (fonts are drawn at SCALE times that)."""
|
||||
|
||||
def __init__(self, fonts):
|
||||
from PIL import Image, ImageDraw
|
||||
self.d = ImageDraw.Draw(Image.new("L", (8, 8)))
|
||||
self.fonts = fonts
|
||||
self._f = {}
|
||||
|
||||
def font(self, key, size, weight=None):
|
||||
k = (key, size, weight)
|
||||
if k not in self._f:
|
||||
self._f[k] = font(self.fonts[key], size, weight)
|
||||
return self._f[k]
|
||||
|
||||
def width(self, fnt, text):
|
||||
return self.d.textlength(text, font=fnt) / SCALE
|
||||
|
||||
def ink(self, fnt, text, x, y, anchor):
|
||||
"""Ink box of text drawn at (x, y) with the anchor, in card pixels."""
|
||||
x0, y0, x1, y1 = self.d.textbbox((x * SCALE, y * SCALE), text, font=fnt, anchor=anchor)
|
||||
return (x0 / SCALE, y0 / SCALE, x1 / SCALE, y1 / SCALE)
|
||||
|
||||
def vextent(self, fnt):
|
||||
"""(rise above the baseline, drop below it) a line in this font may need: the tallest
|
||||
capital with an accent, the deepest descender."""
|
||||
up = -self.d.textbbox((0, 0), "H\u00c9\u00d4l(", font=fnt, anchor="ls")[1] / SCALE
|
||||
down = self.d.textbbox((0, 0), "gjpqy(", font=fnt, anchor="ls")[3] / SCALE
|
||||
return up, down
|
||||
|
||||
|
||||
def short_places(text, measure, fnt, width):
|
||||
"""The places line(s): text as it is, or, where it would take more than PLACES_LINES lines,
|
||||
its first names and a count ("Colorado, Utah and 4 more")."""
|
||||
lines = wrap(lambda t: measure.width(fnt, t), text, width)
|
||||
if len(lines) <= PLACES_LINES:
|
||||
return lines
|
||||
names = [n.strip() for n in text.split(",")]
|
||||
for keep in range(len(names) - 1, 0, -1):
|
||||
more = len(names) - keep
|
||||
head = ", ".join(names[:keep])
|
||||
trial = wrap(lambda t: measure.width(fnt, t), f"{head} and {more} more", width)
|
||||
if len(trial) <= PLACES_LINES:
|
||||
return trial
|
||||
return wrap(lambda t: measure.width(fnt, t), f"{names[0]} and {len(names) - 1} more", width)[:PLACES_LINES]
|
||||
|
||||
|
||||
def flow(measure, name, length, places, width):
|
||||
"""The text column. Returns a list of items (kind, text, font, x, baseline, ink box), the name
|
||||
size, and whether it fits. The name is as large as the block allows between SAFE_TOP and
|
||||
SAFE_BOTTOM; the gaps between name, length and places are fixed ink gaps."""
|
||||
len_f = measure.font("serif", 44, 500)
|
||||
small = measure.font("sans", 30)
|
||||
place_lines = short_places(places, measure, small, width) if places else []
|
||||
len_up, len_down = measure.vextent(len_f)
|
||||
pl_up, pl_down = measure.vextent(small)
|
||||
plc_pitch = 40
|
||||
tail = GAP_NAME + len_up + len_down # name bottom -> length bottom
|
||||
if place_lines:
|
||||
tail += GAP_LENGTH + pl_up + (len(place_lines) - 1) * plc_pitch + pl_down
|
||||
fits = False
|
||||
for size in range(NAME_MAX, NAME_MIN - 1, -NAME_STEP):
|
||||
nf = measure.font("serif", size, 700)
|
||||
lines = wrap_name(measure, nf, name, width)
|
||||
up, down = measure.vextent(nf)
|
||||
pitch = round(size * NAME_LEAD)
|
||||
name_h = up + (len(lines) - 1) * pitch + down
|
||||
ok_w = all(measure.width(nf, ln) <= width for ln in lines)
|
||||
if ok_w and SAFE_TOP + name_h + tail <= SAFE_BOTTOM:
|
||||
fits = True
|
||||
break
|
||||
items = []
|
||||
y = SAFE_TOP + up
|
||||
for ln in lines:
|
||||
items.append(("name", ln, nf, MARGIN, y, measure.ink(nf, ln, MARGIN, y, "ls")))
|
||||
y += pitch
|
||||
y = y - pitch + down + GAP_NAME + len_up
|
||||
text = length
|
||||
items.append(("length", text, len_f, MARGIN, y, measure.ink(len_f, text, MARGIN, y, "ls")))
|
||||
y += len_down + GAP_LENGTH + pl_up
|
||||
for ln in place_lines:
|
||||
items.append(("places", ln, small, MARGIN, y, measure.ink(small, ln, MARGIN, y, "ls")))
|
||||
y += plc_pitch
|
||||
return items, size, fits
|
||||
|
||||
|
||||
def layout(measure, rec, parts):
|
||||
"""Everything drawn on a trail's card, as {"items": [(kind, text, font, x, y, anchor, box)],
|
||||
"track": [polylines in drawn px] or None, "boxes": {kind: [box]}, "name_size", "fits"}."""
|
||||
name, length, places = cards.lines(rec)
|
||||
width = COL_TRACK if parts else COL_FULL
|
||||
items, size, fits = flow(measure, name, length, places, width)
|
||||
track_x0 = TRACK_BOX[0]
|
||||
for wide, x0 in WIDER:
|
||||
if parts and not fits:
|
||||
width, track_x0 = wide, x0
|
||||
items, size, fits = flow(measure, name, length, places, width)
|
||||
items = [(k, t, f, x, y, "ls", box) for k, t, f, x, y, box in items]
|
||||
serif40 = measure.font("serif", 40, 700)
|
||||
sans32 = measure.font("sans", 32)
|
||||
items.append(("header", "Long Hikes", serif40, MARGIN + 92, 62, "la",
|
||||
measure.ink(serif40, "Long Hikes", MARGIN + 92, 62, "la")))
|
||||
items.append(("footer", "longhikes.org", sans32, MARGIN, FOOT_Y, "la",
|
||||
measure.ink(sans32, "longhikes.org", MARGIN, FOOT_Y, "la")))
|
||||
track = None
|
||||
if parts:
|
||||
inset = STROKE / 2 + 1
|
||||
_, y0, x1, y1 = TRACK_BOX
|
||||
x0 = track_x0
|
||||
track = project(parts, ((x0 + inset) * SCALE, (y0 + inset) * SCALE, (x1 - inset) * SCALE, (y1 - inset) * SCALE))
|
||||
return {"items": items, "track": track, "name_size": size, "fits": fits, "width": width, "track_x0": track_x0}
|
||||
|
||||
|
||||
def boxes_of(lay):
|
||||
"""[(kind, box)] of a layout: each text line's ink box, the mark, and the track's ink box."""
|
||||
out = [(k, box) for k, t, f, x, y, a, box in lay["items"]]
|
||||
out.append(("mark", (MARGIN, 52, MARGIN + 76, 52 + 76)))
|
||||
if lay["track"]:
|
||||
xs = [p[0] / SCALE for part in lay["track"] for p in part]
|
||||
ys = [p[1] / SCALE for part in lay["track"] for p in part]
|
||||
h = STROKE / 2
|
||||
out.append(("track", (min(xs) - h, min(ys) - h, max(xs) + h, max(ys) + h)))
|
||||
return out
|
||||
|
||||
|
||||
def parts_of(map_json):
|
||||
@@ -126,45 +293,74 @@ def project(parts, box):
|
||||
return [[(ox + (lon - lon0) * k * s, oy + (lat1 - lat) * s) for lon, lat in part] for part in parts]
|
||||
|
||||
|
||||
def draw_card(rec, map_json, fonts, logo, out_path):
|
||||
from PIL import Image, ImageDraw
|
||||
def finish(img, text, out_path):
|
||||
from PIL import Image
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
img = Image.new("RGB", (W * SCALE, H * SCALE), CREAM)
|
||||
d = ImageDraw.Draw(img)
|
||||
s = SCALE
|
||||
parts = parts_of(map_json) if map_json and os.path.isfile(map_json) else []
|
||||
text_w = 520 if parts else 1030
|
||||
# brand
|
||||
img.paste(logo, (MARGIN * s, 52 * s), logo)
|
||||
d.text(((MARGIN + 92) * s, 62 * s), "Long Hikes", font=font(fonts["serif"], 40, 700), fill=INK)
|
||||
# title
|
||||
name, length, places = cards.lines(rec)
|
||||
size, fnt, lines = fit_title(d, name, fonts["serif"], text_w)
|
||||
y = 168
|
||||
for line in lines:
|
||||
d.text((MARGIN * s, y * s), line, font=fnt, fill=INK)
|
||||
y += int(size * 1.12)
|
||||
y += 14
|
||||
d.text((MARGIN * s, y * s), length, font=font(fonts["serif"], 44, 500), fill=RED)
|
||||
y += 66
|
||||
small = font(fonts["sans"], 30)
|
||||
for line in wrap(d, places, small, text_w * s)[:2]:
|
||||
d.text((MARGIN * s, y * s), line, font=small, fill=MUTED)
|
||||
y += 40
|
||||
# track outline
|
||||
if parts:
|
||||
for part in project(parts, (680 * s, 90 * s, (W - 70) * s, 520 * s)):
|
||||
d.line(part, fill=RED, width=5 * s, joint="curve")
|
||||
# foot
|
||||
d.rectangle((0, (H - 14) * s, W * s, H * s), fill=RED)
|
||||
d.text((MARGIN * s, 548 * s), "longhikes.org", font=font(fonts["sans"], 32), fill=RED)
|
||||
img = img.resize((W, H), Image.LANCZOS)
|
||||
img = img.quantize(colors=24, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
|
||||
info = PngInfo()
|
||||
info.add_text("olt-card", cards.fingerprint(rec))
|
||||
info.add_text("olt-card", text)
|
||||
img.save(out_path, optimize=True, pnginfo=info)
|
||||
|
||||
|
||||
COLOUR = {"name": INK, "header": INK, "length": RED, "places": MUTED, "footer": RED}
|
||||
|
||||
|
||||
def draw_card(rec, map_json, fonts, logo, out_path, measure=None):
|
||||
from PIL import Image, ImageDraw
|
||||
img = Image.new("RGB", (W * SCALE, H * SCALE), CREAM)
|
||||
d = ImageDraw.Draw(img)
|
||||
s = SCALE
|
||||
measure = measure or Measure(fonts)
|
||||
parts = parts_of(map_json) if map_json and os.path.isfile(map_json) else []
|
||||
lay = layout(measure, rec, parts)
|
||||
img.paste(logo, (MARGIN * s, 52 * s), logo)
|
||||
for kind, text, fnt, x, y, anchor, box in lay["items"]:
|
||||
d.text((x * s, y * s), text, font=fnt, fill=COLOUR[kind], anchor=anchor)
|
||||
for part in lay["track"] or []:
|
||||
d.line(part, fill=RED, width=STROKE * s, joint="curve")
|
||||
d.rectangle((0, (H - 14) * s, W * s, H * s), fill=RED)
|
||||
finish(img, cards.fingerprint(rec), out_path)
|
||||
|
||||
|
||||
def site_layout(measure, site):
|
||||
"""The site card: the name and the headline (from web/site.toml), the headline as large as
|
||||
fits the safe area."""
|
||||
name, headline = cards.site_lines(site)
|
||||
top = SAFE_TOP + 40
|
||||
for size in range(NAME_MAX, NAME_MIN - 1, -NAME_STEP):
|
||||
nf = measure.font("serif", size, 700)
|
||||
lines = wrap(lambda t: measure.width(nf, t), headline, COL_FULL)
|
||||
up, down = measure.vextent(nf)
|
||||
pitch = round(size * NAME_LEAD)
|
||||
if top + up + (len(lines) - 1) * pitch + down <= SAFE_BOTTOM:
|
||||
break
|
||||
items, y = [], top + up
|
||||
for ln in lines:
|
||||
items.append(("name", ln, nf, MARGIN, y, "ls", measure.ink(nf, ln, MARGIN, y, "ls")))
|
||||
y += pitch
|
||||
serif40 = measure.font("serif", 40, 700)
|
||||
items.append(("header", name, serif40, MARGIN + 92, 62, "la", measure.ink(serif40, name, MARGIN + 92, 62, "la")))
|
||||
host = (site.base_url or "").split("://")[-1]
|
||||
if host:
|
||||
sans32 = measure.font("sans", 32)
|
||||
items.append(("footer", host, sans32, MARGIN, FOOT_Y, "la", measure.ink(sans32, host, MARGIN, FOOT_Y, "la")))
|
||||
return {"items": items, "track": None, "name_size": size, "width": COL_FULL}
|
||||
|
||||
|
||||
def draw_site_card(site, fonts, logo, out_path):
|
||||
"""The site card, assets/og.png."""
|
||||
from PIL import Image, ImageDraw
|
||||
img = Image.new("RGB", (W * SCALE, H * SCALE), CREAM)
|
||||
d = ImageDraw.Draw(img)
|
||||
s = SCALE
|
||||
img.paste(logo, (MARGIN * s, 52 * s), logo)
|
||||
for kind, text, fnt, x, y, anchor, box in site_layout(Measure(fonts), site)["items"]:
|
||||
d.text((x * s, y * s), text, font=fnt, fill=COLOUR[kind], anchor=anchor)
|
||||
d.rectangle((0, (H - 14) * s, W * s, H * s), fill=RED)
|
||||
finish(img, cards.site_fingerprint(site), out_path)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="Make web/cards/<id>.png for every trail.")
|
||||
ap.add_argument("--site", default=os.path.join(ROOT, "_site"), help="a built site, for each trail's map.json")
|
||||
@@ -195,6 +391,13 @@ def main(argv=None):
|
||||
continue
|
||||
draw_card(rec, map_json, fonts, logo, dst)
|
||||
made += 1
|
||||
site_cfg = site_mod.from_file(os.path.join(WEB, "site.toml"))
|
||||
og = os.path.join(WEB, "assets", "og.png")
|
||||
if (not only
|
||||
and (args.force or cards.stored_fingerprint(og) != cards.site_fingerprint(site_cfg))):
|
||||
with tempfile.TemporaryDirectory() as tmp2:
|
||||
draw_site_card(site_cfg, load_fonts(tmp2), mark(tmp2), og)
|
||||
print("site card drawn: web/assets/og.png")
|
||||
ids = {r["id"] for r in recs}
|
||||
removed = 0
|
||||
for name in sorted(os.listdir(out_dir)):
|
||||
|
||||
+21
-10
@@ -1,9 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Make the small PNG logo thumbnails the site shows in lists.
|
||||
|
||||
For every <id>/shield.png in the repository root, writes web/thumbs/<id>.png,
|
||||
scaled to fit within 256 x 256 px (never enlarged), metadata stripped and
|
||||
transparency kept. Needs ImageMagick 7 (`magick`) on the PATH; runs optipng
|
||||
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.
|
||||
|
||||
@@ -25,19 +27,28 @@ MAX_SIDE = 256
|
||||
|
||||
|
||||
def sources():
|
||||
"""{id: path} for each <id>/shield.png directly under the repository root."""
|
||||
"""{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)):
|
||||
path = os.path.join(ROOT, name, "shield.png")
|
||||
if not name.startswith((".", "_")) and os.path.isfile(path):
|
||||
found[name] = path
|
||||
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."""
|
||||
cmd = ["magick", src, "-strip", "-resize", f"{MAX_SIDE}x{MAX_SIDE}>",
|
||||
"PNG32:" + dst]
|
||||
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:
|
||||
@@ -50,7 +61,7 @@ def make_thumb(src, dst):
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="Make web/thumbs/<id>.png from each <id>/shield.png.")
|
||||
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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user