Keep asked-for texts clear of the credit band; answer review round 1
At 400 to 640 px the credit band, held to 12 px after scaling, covered the date, the circuit line, the session label and the season's subtitle. The band is now laid out first and every bottom text, the photo inset and the poster's dark band are lifted by as much as it would cover them, which at full size is nothing, so classic draws as before; the bottom checker is drawn last again, over the track's end. A first render now draws from the layer as kept, so it matches every later render of its key, and the ETag is weak all the same. A Commons file's SHA-1 is kept beside the layers and asked once, so photo pictures need no Commons request after a restart. The USGS credit carries no prefix, and /licences names a layout switched to the map among OpenStreetMap's uses. Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
+115
-44
@@ -10,6 +10,7 @@ and kept nowhere.
|
||||
Which source, which options and which keys: poster_sources.py and poster_options.py (standard library only).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
@@ -314,23 +315,41 @@ def stitch_tiles(source: ps.MapSource, zoom: int, left: int, top: int, width: in
|
||||
|
||||
|
||||
class Commons:
|
||||
"""Wikimedia Commons: one API request at a time, at most five a second; at most two downloads at once."""
|
||||
"""Wikimedia Commons: one API request at a time, at most five a second; at most two downloads at once.
|
||||
|
||||
A file's SHA-1 and address, once read, are kept beside the layers (`commons-sha1/`), so a photo layer is found
|
||||
after a restart without asking the API; a file is asked once, however many requests want it at the same time."""
|
||||
API = "https://commons.wikimedia.org/w/api.php"
|
||||
WIDTH = 3840 # a thumbnail step wide enough to cover a portrait poster from a landscape photo
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, layers: LayerStore):
|
||||
self.layers = layers
|
||||
self._api_lock = threading.Lock()
|
||||
self._last_api = 0.0
|
||||
self._downloads = threading.BoundedSemaphore(2)
|
||||
self._info: dict[str, dict] = {} # file → its address and SHA-1, asked once per run
|
||||
self._info: dict[str, dict] = {} # file → its address and SHA-1
|
||||
|
||||
@staticmethod
|
||||
def _kept_key(file: str) -> str:
|
||||
return f"commons-sha1/{hashlib.sha256(file.encode()).hexdigest()[:16]}" # a title may hold any character
|
||||
|
||||
def _kept(self, file: str) -> Optional[dict]:
|
||||
kept = self.layers.read_json(self._kept_key(file))
|
||||
if kept and kept.get("file") == file and kept.get("sha1") and kept.get("url"):
|
||||
return {"sha1": kept["sha1"], "url": kept["url"]}
|
||||
return None
|
||||
|
||||
def info(self, file: str) -> Optional[dict]:
|
||||
if file in self._info:
|
||||
return self._info[file]
|
||||
found = self._info.get(file) or self._kept(file)
|
||||
if found:
|
||||
self._info[file] = found
|
||||
return found
|
||||
query = urllib.parse.urlencode({"action": "query", "format": "json", "formatversion": "2",
|
||||
"prop": "imageinfo", "iiprop": "url|sha1|size",
|
||||
"iiurlwidth": str(self.WIDTH), "titles": f"File:{file}"})
|
||||
with self._api_lock:
|
||||
if file in self._info: # asked meanwhile for another request
|
||||
return self._info[file]
|
||||
wait = self._last_api + 0.2 - time.monotonic()
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
@@ -341,8 +360,10 @@ class Commons:
|
||||
except Exception as e:
|
||||
logger.warning(f"Commons gave no file information for {file!r}: {e}")
|
||||
return None
|
||||
found = {"sha1": info["sha1"], "url": info.get("thumburl") or info["url"]}
|
||||
self._info[file] = found
|
||||
found = {"sha1": info["sha1"], "url": info.get("thumburl") or info["url"]}
|
||||
self.layers.write_json(self._kept_key(file), {"file": file, **found})
|
||||
self._info[file] = found
|
||||
logger.info(f"Commons file {file!r}: SHA-1 {found['sha1']} read and kept")
|
||||
return found
|
||||
|
||||
def download(self, url: str) -> Optional[bytes]:
|
||||
@@ -376,6 +397,19 @@ def cover(img: Image.Image, size: tuple[int, int]) -> Image.Image:
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- the service
|
||||
|
||||
@dataclass
|
||||
class CreditBand:
|
||||
"""The credit line laid out: its font, its wrapped lines, and the band's height."""
|
||||
font: ImageFont.FreeTypeFont
|
||||
lines: list[str]
|
||||
line_h: int
|
||||
pad: int
|
||||
height: int
|
||||
|
||||
|
||||
BAND_GAP = 12 # between the credit band and the lowest text above it
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rendered:
|
||||
data: bytes
|
||||
@@ -407,7 +441,7 @@ class PostersService:
|
||||
logger.warning("No bundled font found — poster text will use PIL's default bitmap font")
|
||||
self.layers = LayerStore(layers_dir)
|
||||
self.store = PosterStore(posters_dir)
|
||||
self.commons = Commons()
|
||||
self.commons = Commons(self.layers)
|
||||
self._layer_locks: dict[str, threading.Lock] = {}
|
||||
self._layer_locks_guard = threading.Lock()
|
||||
self._picks: dict[Path, tuple[float, dict]] = {}
|
||||
@@ -501,7 +535,8 @@ class PostersService:
|
||||
return None
|
||||
self.layers.write_image(key, ext, img)
|
||||
logger.info(f"Layer {key}: made and kept")
|
||||
return img
|
||||
# Drawn from the layer as kept (a JPEG is lossy), so a first render and every later one agree.
|
||||
return self.layers.read_image(key, ext) or img
|
||||
|
||||
def _map_layer(self, source: ps.MapSource, geo: Geo, frame: str, zoom: int) -> Layer:
|
||||
key = po.map_layer_key(source.key, geo.trace_hash, frame, zoom)
|
||||
@@ -579,13 +614,14 @@ class PostersService:
|
||||
draw.rectangle([x, yy, x + CHECKER_SQ, yy + CHECKER_SQ], fill=WHITE if (col + row) % 2 == 0 else BG)
|
||||
|
||||
@staticmethod
|
||||
def _dim_overlay(kind: str, size: tuple[int, int], dim: float) -> Image.Image:
|
||||
def _dim_overlay(kind: str, size: tuple[int, int], dim: float, lift: int = 0) -> Image.Image:
|
||||
"""The darkening over a map or photo: each kind keeps its shape (the poster's text bands darker than the
|
||||
band behind the track, the season's gradient), scaled by dim; the classic dim draws it as it always was."""
|
||||
band behind the track, the season's gradient), scaled by dim; the classic dim draws it as it always was. The
|
||||
poster's bottom band rises with the texts it carries when the credit band lifts them (`lift`)."""
|
||||
w, h = size
|
||||
scale = dim / po.CLASSIC_DIM[kind]
|
||||
if kind == "race":
|
||||
base = [200 if y < 540 or y >= 1300 else 110 for y in range(h)]
|
||||
base = [200 if y < 540 or y >= 1300 - lift else 110 for y in range(h)]
|
||||
elif kind == "season":
|
||||
base = [220 - (y * 220 // 500) if y < 500 else min((y - 1100) * 220 // (h - 1100), 220) if y > 1100 else 60
|
||||
for y in range(h)]
|
||||
@@ -606,9 +642,11 @@ class PostersService:
|
||||
d.line(pts + [pts[0]], fill=(0, 0, 0), width=width + 4, joint="curve")
|
||||
d.line(pts + [pts[0]], fill=_hex(colour), width=width, joint="curve")
|
||||
|
||||
def _draw_inset(self, img: Image.Image, frame: str, points: list, track: tuple[str, int]) -> None:
|
||||
"""The track over a photo: the trace fitted to a box at the bottom right, on a half-black panel."""
|
||||
def _draw_inset(self, img: Image.Image, frame: str, points: list, track: tuple[str, int], clear: int) -> None:
|
||||
"""The track over a photo: the trace fitted to a box at the bottom right, on a half-black panel, kept above
|
||||
`clear` (the credit band's top)."""
|
||||
size, margin, bottom = INSET[frame]
|
||||
bottom = min(bottom, clear)
|
||||
x0, y0 = img.width - margin - size, bottom - size
|
||||
panel = Image.new("RGBA", (size, size), (0, 0, 0, 128))
|
||||
img.paste(panel, (x0, y0), panel)
|
||||
@@ -631,33 +669,43 @@ class PostersService:
|
||||
d.rectangle([0, 0, size - 1, size - 1], outline=(255, 255, 255, 200), width=2)
|
||||
img.paste(inset, (img.width - size - margin, top))
|
||||
|
||||
def _draw_credit(self, img: Image.Image, credit: str, bottom: int, scale: float) -> None:
|
||||
"""The credit line on a dark band, at least CREDIT_MIN_PX high on the picture as served, wrapped."""
|
||||
def _credit_band(self, credit: str, width: int, scale: float) -> Optional[CreditBand]:
|
||||
"""The credit line's band, laid out before anything is drawn above it: its font at least CREDIT_MIN_PX high
|
||||
on the picture as served, wrapped to the picture's width. None when the picture has no source."""
|
||||
if not credit:
|
||||
return
|
||||
return None
|
||||
size = 14
|
||||
while self._text_height(size) * scale < CREDIT_MIN_PX:
|
||||
size += 1
|
||||
font = self._font(size, self.credit_font_path)
|
||||
draw = ImageDraw.Draw(img)
|
||||
margin = max(12, size)
|
||||
lines, line = [], ""
|
||||
for word in credit.split(" "):
|
||||
candidate = f"{line} {word}".strip()
|
||||
if line and draw.textlength(candidate, font) > img.width - 2 * margin:
|
||||
if line and font.getlength(candidate) > width - 2 * margin:
|
||||
lines.append(line)
|
||||
line = word
|
||||
else:
|
||||
line = candidate
|
||||
lines.append(line)
|
||||
line_h = round(size * 1.25)
|
||||
pad = max(4, size // 3)
|
||||
band_h = len(lines) * line_h + 2 * pad
|
||||
band = Image.new("RGBA", (img.width, band_h), (0, 0, 0, 170))
|
||||
img.paste(band, (0, bottom - band_h), band)
|
||||
for i, text in enumerate(lines):
|
||||
x = (img.width - draw.textlength(text, font)) / 2
|
||||
draw.text((x, bottom - band_h + pad + i * line_h), text, font=font, fill=(225, 225, 225))
|
||||
line_h, pad = round(size * 1.25), max(4, size // 3)
|
||||
return CreditBand(font, lines, line_h, pad, len(lines) * line_h + 2 * pad)
|
||||
|
||||
@staticmethod
|
||||
def _draw_credit(img: Image.Image, band: Optional[CreditBand], bottom: int) -> None:
|
||||
"""The credit line on its dark band, ending at `bottom` (the bottom strip's top, or the picture's foot)."""
|
||||
if band is None:
|
||||
return
|
||||
layer = Image.new("RGBA", (img.width, band.height), (0, 0, 0, 170))
|
||||
img.paste(layer, (0, bottom - band.height), layer)
|
||||
draw = ImageDraw.Draw(img)
|
||||
for i, text in enumerate(band.lines):
|
||||
x = (img.width - draw.textlength(text, band.font)) / 2
|
||||
draw.text((x, bottom - band.height + band.pad + i * band.line_h), text, font=band.font, fill=(225, 225, 225))
|
||||
|
||||
def _text_bottom(self, text: str, y: int, size: int) -> int:
|
||||
"""Where a text drawn at y in the poster font ends."""
|
||||
return y + self._font(size).getbbox(text)[3]
|
||||
|
||||
def _text_height(self, size: int) -> int:
|
||||
box = self._font(size, self.credit_font_path).getbbox("Ag")
|
||||
@@ -780,6 +828,22 @@ class PostersService:
|
||||
tint: Optional[str] = None) -> Image.Image:
|
||||
size = po.FRAMES[frame]
|
||||
w, h = size
|
||||
show = options.show
|
||||
accent = _hex(options.accent)
|
||||
# The credit band is laid out first: every text at the bottom is lifted by as much as the band would cover
|
||||
# it (nothing at full size in either style; more as `width` makes the band taller).
|
||||
bottom = h - CHECKER_H if options.checker else h
|
||||
band = self._credit_band(credit, w, options.width / w)
|
||||
clear = bottom - (band.height + BAND_GAP if band else 0)
|
||||
place = " · ".join(texts[k] for k in ("circuit", "locality") if k in show) if kind == "race" else ""
|
||||
date = texts["date"] if kind == "race" and "date" in show else ""
|
||||
bottoms = []
|
||||
if place:
|
||||
bottoms.append(self._text_bottom(place, h - 210, 28))
|
||||
if date:
|
||||
bottoms.append(self._text_bottom(date, h - 170, 32))
|
||||
lift = max(0, max(bottoms, default=0) - clear) # the race poster's place line and date
|
||||
|
||||
img = Image.new("RGB", size, BG)
|
||||
if background is not None:
|
||||
if is_photo:
|
||||
@@ -787,17 +851,14 @@ class PostersService:
|
||||
else:
|
||||
background = recolour(background, tint or options.bg)
|
||||
img = Image.alpha_composite(background.convert("RGBA"),
|
||||
self._dim_overlay(kind, size, options.dim)).convert("RGB")
|
||||
self._dim_overlay(kind, size, options.dim, lift)).convert("RGB")
|
||||
draw = ImageDraw.Draw(img)
|
||||
show = options.show
|
||||
accent = _hex(options.accent)
|
||||
if options.checker:
|
||||
self._checker_strip(draw, 0, w)
|
||||
self._checker_strip(draw, h - CHECKER_H, w)
|
||||
|
||||
if outline and options.track:
|
||||
if is_photo and background is not None:
|
||||
self._draw_inset(img, frame, outline, options.track)
|
||||
self._draw_inset(img, frame, outline, options.track, clear)
|
||||
else:
|
||||
self._draw_track(img, outline, options.track)
|
||||
|
||||
@@ -807,7 +868,9 @@ class PostersService:
|
||||
if "name" in show:
|
||||
self._centered(draw, texts["name"], 240, 240, WHITE)
|
||||
if "subtitle" in show:
|
||||
self._centered(draw, texts["subtitle"], h - 200, 48, WHITE)
|
||||
y = h - 200
|
||||
y -= max(0, self._text_bottom(texts["subtitle"], y, 48) - clear)
|
||||
self._centered(draw, texts["subtitle"], y, 48, WHITE)
|
||||
elif kind == "race":
|
||||
if "wordmark" in show:
|
||||
self._centered(draw, texts["wordmark"], 110, 88, accent)
|
||||
@@ -817,22 +880,23 @@ class PostersService:
|
||||
self._centered(draw, texts["name"], 300, 110, WHITE)
|
||||
if "subtitle" in show:
|
||||
self._centered(draw, texts["subtitle"], 440, 44, GREY)
|
||||
place = " · ".join(texts[k] for k in ("circuit", "locality") if k in show)
|
||||
if place:
|
||||
self._centered(draw, place, h - 210, 28, GREY)
|
||||
if "date" in show and texts["date"]:
|
||||
self._centered(draw, texts["date"], h - 170, 32, WHITE)
|
||||
self._centered(draw, place, h - 210 - lift, 28, GREY)
|
||||
if date:
|
||||
self._centered(draw, date, h - 170 - lift, 32, WHITE)
|
||||
else:
|
||||
self._draw_thumb_texts(draw, texts, show, accent, CHECKER_H if options.checker else 0)
|
||||
self._draw_thumb_texts(draw, texts, show, accent, clear)
|
||||
|
||||
if locator is not None:
|
||||
self._draw_locator(img, frame, locator)
|
||||
self._draw_credit(img, credit, h - CHECKER_H if options.checker else h, options.width / w)
|
||||
self._draw_credit(img, band, bottom)
|
||||
if options.checker:
|
||||
self._checker_strip(draw, h - CHECKER_H, w) # last, over the track's end, as it always was
|
||||
return img
|
||||
|
||||
def _draw_thumb_texts(self, draw: ImageDraw.ImageDraw, texts: dict, show: frozenset, accent, lift: int) -> None:
|
||||
def _draw_thumb_texts(self, draw: ImageDraw.ImageDraw, texts: dict, show: frozenset, accent, clear: int) -> None:
|
||||
"""The thumb's texts: the heading top left, the session label (and the date under it) bottom left, lifted
|
||||
above the bottom checker strip when it is drawn."""
|
||||
above `clear` (the credit band's top) by as much as they would reach under it."""
|
||||
x = 80
|
||||
if "wordmark" in show:
|
||||
draw.text((x, 60), texts["wordmark"], fill=accent, font=self._font(40))
|
||||
@@ -852,12 +916,19 @@ class PostersService:
|
||||
label, sess_size = texts["session"].upper(), 90
|
||||
while sess_size > 50 and draw.textlength(label, self._font(sess_size)) > 1300:
|
||||
sess_size -= 6
|
||||
sess_y = THUMB_H - 130 - sess_size - lift
|
||||
sess_y = THUMB_H - 130 - sess_size
|
||||
date = texts["date"] if "date" in show else ""
|
||||
bottoms = []
|
||||
if "session" in show:
|
||||
bottoms.append(self._text_bottom(label, sess_y, sess_size))
|
||||
if date:
|
||||
bottoms.append(self._text_bottom(date, sess_y + sess_size + 14, 36))
|
||||
sess_y -= max(0, max(bottoms, default=0) - clear)
|
||||
if "session" in show:
|
||||
draw.rectangle([x, sess_y - 16, x + 120, sess_y - 8], fill=RED) # a thin bar above the session label
|
||||
draw.text((x, sess_y), label, fill=WHITE, font=self._font(sess_size))
|
||||
if "date" in show and texts["date"]:
|
||||
draw.text((x, sess_y + sess_size + 14), texts["date"], fill=GREY, font=self._font(36))
|
||||
if date:
|
||||
draw.text((x, sess_y + sess_size + 14), date, fill=GREY, font=self._font(36))
|
||||
|
||||
# ------------------------------------------------------------------ kometa metadata
|
||||
|
||||
|
||||
Reference in New Issue
Block a user