| 1 | """Deterministische omslagen uit de titel: statische SVG, zonder verhaaltekst.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import hashlib |
| 6 | import math |
| 7 | import re |
| 8 | from pathlib import Path |
| 9 | |
| 10 | # 2:3, een gangbaar coverformaat in leesapps. |
| 11 | WIDTH = 240 |
| 12 | HEIGHT = 360 |
| 13 | MARGIN_X = 18 |
| 14 | MARGIN_Y = 22 |
| 15 | TEXT_AREA_BOTTOM = 24 |
| 16 | BAND_PADDING = 16 |
| 17 | |
| 18 | |
| 19 | def title_key(title: str) -> str: |
| 20 | return (title or "").strip() or "Untitled" |
| 21 | |
| 22 | |
| 23 | def title_hash(title: str) -> str: |
| 24 | return hashlib.sha256(title_key(title).encode("utf-8")).hexdigest() |
| 25 | |
| 26 | |
| 27 | def cover_relpath(title: str) -> str: |
| 28 | digest = title_hash(title) |
| 29 | return f"covers/{digest[:2]}/{digest[:20]}.svg" |
| 30 | |
| 31 | |
| 32 | def _hsl_to_hex(h: float, s: float, l: float) -> str: |
| 33 | """h in [0, 360), s en l in [0, 1].""" |
| 34 | h = h % 360 |
| 35 | c = (1 - abs(2 * l - 1)) * s |
| 36 | x = c * (1 - abs((h / 60) % 2 - 1)) |
| 37 | m = l - c / 2 |
| 38 | if h < 60: |
| 39 | r, g, b = c, x, 0 |
| 40 | elif h < 120: |
| 41 | r, g, b = x, c, 0 |
| 42 | elif h < 180: |
| 43 | r, g, b = 0, c, x |
| 44 | elif h < 240: |
| 45 | r, g, b = 0, x, c |
| 46 | elif h < 300: |
| 47 | r, g, b = x, 0, c |
| 48 | else: |
| 49 | r, g, b = c, 0, x |
| 50 | return "#{:02x}{:02x}{:02x}".format(round((r + m) * 255), round((g + m) * 255), round((b + m) * 255)) |
| 51 | |
| 52 | |
| 53 | def palette(title: str) -> dict: |
| 54 | digest = title_hash(title) |
| 55 | nums = [int(digest[i : i + 2], 16) for i in range(0, 16, 2)] |
| 56 | h1 = nums[0] / 255 * 360 |
| 57 | h2 = (h1 + 28 + nums[1] / 255 * 80) % 360 |
| 58 | s1 = 0.48 + nums[2] / 255 * 0.32 |
| 59 | s2 = 0.42 + nums[3] / 255 * 0.32 |
| 60 | l1 = 0.30 + nums[4] / 255 * 0.18 |
| 61 | l2 = 0.22 + nums[5] / 255 * 0.16 |
| 62 | variant = nums[6] % 6 |
| 63 | angle = nums[7] / 255 * 360 |
| 64 | return { |
| 65 | "c1": _hsl_to_hex(h1, s1, l1), |
| 66 | "c2": _hsl_to_hex(h2, s2, l2), |
| 67 | "c3": _hsl_to_hex((h1 + 180) % 360, 0.35, 0.55), |
| 68 | "variant": variant, |
| 69 | "angle": angle, |
| 70 | "digest": digest, |
| 71 | } |
| 72 | |
| 73 | |
| 74 | def _char_width(font_size: int) -> float: |
| 75 | # Ruime schatting voor een vet sans-serif, zodat regels niet over de rand lopen. |
| 76 | return font_size * 0.62 |
| 77 | |
| 78 | |
| 79 | def max_chars_for(font_size: int) -> int: |
| 80 | usable = WIDTH - 2 * MARGIN_X |
| 81 | return max(8, int(usable / _char_width(font_size))) |
| 82 | |
| 83 | |
| 84 | def wrap_title(title: str, max_chars: int, max_lines: int) -> list[str]: |
| 85 | """Breek de titel op woorden, en midden in een te lang woord.""" |
| 86 | text = re.sub(r"\s+", " ", title_key(title)).strip() |
| 87 | if not text: |
| 88 | return ["Untitled"] |
| 89 | |
| 90 | def break_word(word: str) -> list[str]: |
| 91 | if len(word) <= max_chars: |
| 92 | return [word] |
| 93 | parts = [] |
| 94 | rest = word |
| 95 | while len(rest) > max_chars: |
| 96 | # Laat ruimte voor een koppelteken, behalve als we later ellipsis zetten. |
| 97 | cut = max_chars - 1 |
| 98 | parts.append(rest[:cut] + "-") |
| 99 | rest = rest[cut:] |
| 100 | if rest: |
| 101 | parts.append(rest) |
| 102 | return parts |
| 103 | |
| 104 | words: list[str] = [] |
| 105 | for raw in text.split(" "): |
| 106 | words.extend(break_word(raw)) |
| 107 | |
| 108 | lines: list[str] = [] |
| 109 | current = "" |
| 110 | for word in words: |
| 111 | trial = word if not current else current + " " + word |
| 112 | if len(trial) <= max_chars: |
| 113 | current = trial |
| 114 | continue |
| 115 | if current: |
| 116 | lines.append(current) |
| 117 | current = word |
| 118 | if current: |
| 119 | lines.append(current) |
| 120 | |
| 121 | if len(lines) > max_lines: |
| 122 | lines = lines[:max_lines] |
| 123 | last = lines[-1] |
| 124 | budget = max(1, max_chars - 1) |
| 125 | if len(last) > budget: |
| 126 | last = last[:budget].rstrip(" -") |
| 127 | lines[-1] = last.rstrip(" -") + "…" |
| 128 | return lines |
| 129 | |
| 130 | |
| 131 | def choose_layout(title: str) -> tuple[int, list[str]]: |
| 132 | """Kies een lettergrootte zodat de titel past; zo nodig ellipsis.""" |
| 133 | for font_size, max_lines in ((26, 5), (22, 6), (18, 7), (16, 8)): |
| 134 | lines = wrap_title(title, max_chars_for(font_size), max_lines=99) |
| 135 | if len(lines) <= max_lines and not (lines and lines[-1].endswith("…")): |
| 136 | return font_size, lines |
| 137 | font_size, max_lines = 16, 8 |
| 138 | return font_size, wrap_title(title, max_chars_for(font_size), max_lines) |
| 139 | |
| 140 | |
| 141 | def _esc(text: str) -> str: |
| 142 | return ( |
| 143 | text.replace("&", "&") |
| 144 | .replace("<", "<") |
| 145 | .replace(">", ">") |
| 146 | .replace('"', """) |
| 147 | ) |
| 148 | |
| 149 | |
| 150 | def _background(pal: dict, gid: str) -> str: |
| 151 | c1, c2, c3 = pal["c1"], pal["c2"], pal["c3"] |
| 152 | variant = pal["variant"] |
| 153 | angle = pal["angle"] |
| 154 | rad = math.radians(angle) |
| 155 | x2 = 0.5 + math.cos(rad) / 2 |
| 156 | y2 = 0.5 + math.sin(rad) / 2 |
| 157 | defs = [ |
| 158 | f'<linearGradient id="{gid}" x1="0" y1="0" x2="{x2:.3f}" y2="{y2:.3f}">', |
| 159 | f'<stop offset="0%" stop-color="{c1}"/>', |
| 160 | f'<stop offset="100%" stop-color="{c2}"/>', |
| 161 | "</linearGradient>", |
| 162 | ] |
| 163 | body = [f'<rect width="{WIDTH}" height="{HEIGHT}" fill="url(#{gid})"/>'] |
| 164 | if variant == 1: |
| 165 | body.append( |
| 166 | f'<circle cx="{WIDTH * 0.78:.0f}" cy="{HEIGHT * 0.22:.0f}" r="90" fill="{c3}" fill-opacity="0.28"/>' |
| 167 | ) |
| 168 | body.append( |
| 169 | f'<circle cx="{WIDTH * 0.12:.0f}" cy="{HEIGHT * 0.7:.0f}" r="70" fill="{c1}" fill-opacity="0.25"/>' |
| 170 | ) |
| 171 | elif variant == 2: |
| 172 | pid = gid + "p" |
| 173 | defs.append( |
| 174 | f'<pattern id="{pid}" width="28" height="28" patternUnits="userSpaceOnUse"' |
| 175 | f' patternTransform="rotate({angle:.0f})">' |
| 176 | f'<rect width="14" height="28" fill="{c3}" fill-opacity="0.22"/>' |
| 177 | "</pattern>" |
| 178 | ) |
| 179 | body.append(f'<rect width="{WIDTH}" height="{HEIGHT}" fill="url(#{pid})"/>') |
| 180 | elif variant == 3: |
| 181 | body.append( |
| 182 | f'<circle cx="{WIDTH * 0.3:.0f}" cy="{HEIGHT * 0.32:.0f}" r="110" fill="{c3}" fill-opacity="0.22"/>' |
| 183 | ) |
| 184 | body.append( |
| 185 | f'<circle cx="{WIDTH * 0.85:.0f}" cy="{HEIGHT * 0.55:.0f}" r="95" fill="{c2}" fill-opacity="0.28"/>' |
| 186 | ) |
| 187 | elif variant == 4: |
| 188 | body.append( |
| 189 | f'<rect x="40" y="40" width="160" height="160" rx="8" transform="rotate(32 120 120)" ' |
| 190 | f'fill="{c3}" fill-opacity="0.18"/>' |
| 191 | ) |
| 192 | body.append( |
| 193 | f'<rect x="20" y="160" width="130" height="130" rx="8" transform="rotate(-18 85 225)" ' |
| 194 | f'fill="{c1}" fill-opacity="0.22"/>' |
| 195 | ) |
| 196 | elif variant == 5: |
| 197 | for i, y in enumerate(range(0, HEIGHT, 36)): |
| 198 | if i % 2 == 0: |
| 199 | body.append(f'<rect x="0" y="{y}" width="{WIDTH}" height="18" fill="{c3}" fill-opacity="0.16"/>') |
| 200 | return "<defs>" + "".join(defs) + "</defs>" + "".join(body) |
| 201 | |
| 202 | |
| 203 | def render_svg(title: str) -> str: |
| 204 | pal = palette(title) |
| 205 | font_size, lines = choose_layout(title) |
| 206 | line_height = round(font_size * 1.22) |
| 207 | text_block = line_height * len(lines) |
| 208 | band_top = HEIGHT - TEXT_AREA_BOTTOM - text_block - BAND_PADDING * 2 |
| 209 | band_top = max(HEIGHT * 0.42, band_top) |
| 210 | band_height = HEIGHT - band_top |
| 211 | gid = "g" + pal["digest"][:10] |
| 212 | # Tekst onderaan, gecentreerd, op de donkere band. |
| 213 | first_baseline = band_top + BAND_PADDING + font_size |
| 214 | tspans = [] |
| 215 | for i, line in enumerate(lines): |
| 216 | y = first_baseline + i * line_height |
| 217 | tspans.append( |
| 218 | f'<tspan x="{WIDTH // 2}" y="{y}">{_esc(line)}</tspan>' |
| 219 | ) |
| 220 | svg = ( |
| 221 | f'<svg xmlns="http://www.w3.org/2000/svg" width="{WIDTH}" height="{HEIGHT}" ' |
| 222 | f'viewBox="0 0 {WIDTH} {HEIGHT}" role="img" aria-label="{_esc(title_key(title))}">' |
| 223 | f"{_background(pal, gid)}" |
| 224 | f'<rect x="0" y="{band_top:.1f}" width="{WIDTH}" height="{band_height:.1f}" fill="#0b1020" fill-opacity="0.55"/>' |
| 225 | f'<text font-family="Trebuchet MS, Segoe UI, sans-serif" font-size="{font_size}" ' |
| 226 | f'font-weight="700" fill="#f7f4ef" text-anchor="middle" ' |
| 227 | f'stroke="#0b1020" stroke-width="0.8" paint-order="stroke">' |
| 228 | + "".join(tspans) |
| 229 | + "</text></svg>\n" |
| 230 | ) |
| 231 | return svg |
| 232 | |
| 233 | |
| 234 | def prune_unused_covers(dest_root: Path, keep: set[str]) -> None: |
| 235 | root = Path(dest_root) / "covers" |
| 236 | if not root.exists(): |
| 237 | return |
| 238 | keep_stems = {Path(name).stem for name in keep} |
| 239 | for path in list(root.rglob("*.svg")) + list(root.rglob("*.png")): |
| 240 | if path.stem not in keep_stems: |
| 241 | path.unlink() |
| 242 | for folder in sorted(root.rglob("*"), reverse=True): |
| 243 | if folder.is_dir() and not any(folder.iterdir()): |
| 244 | folder.rmdir() |
| 245 | |
| 246 | |
| 247 | # Alleen voor de tests: hoe hoog staat de laatste regel, past alles in het vlak? |
| 248 | def text_bounds(title: str) -> dict: |
| 249 | font_size, lines = choose_layout(title) |
| 250 | line_height = round(font_size * 1.22) |
| 251 | text_block = line_height * len(lines) |
| 252 | band_top = max(HEIGHT * 0.42, HEIGHT - TEXT_AREA_BOTTOM - text_block - BAND_PADDING * 2) |
| 253 | first_baseline = band_top + BAND_PADDING + font_size |
| 254 | last_baseline = first_baseline + (len(lines) - 1) * line_height |
| 255 | # Ruime descent (~0.25 em) onder de baseline. |
| 256 | last_bottom = last_baseline + font_size * 0.3 |
| 257 | return { |
| 258 | "font_size": font_size, |
| 259 | "lines": lines, |
| 260 | "line_max_chars": max_chars_for(font_size), |
| 261 | "band_top": band_top, |
| 262 | "last_bottom": last_bottom, |
| 263 | "width": WIDTH, |
| 264 | "height": HEIGHT, |
| 265 | } |
| 266 | |
| 267 | |
| 268 | FONT_PATH = Path(__file__).resolve().parent / "fonts" / "DejaVuSans-Bold.ttf" |
| 269 | |
| 270 | |
| 271 | def _font(size: int): |
| 272 | from PIL import ImageFont |
| 273 | |
| 274 | if FONT_PATH.is_file(): |
| 275 | return ImageFont.truetype(str(FONT_PATH), size=size) |
| 276 | return ImageFont.load_default() |
| 277 | |
| 278 | |
| 279 | def _lerp(a: tuple[int, int, int], b: tuple[int, int, int], t: float) -> tuple[int, int, int]: |
| 280 | return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3)) # type: ignore[return-value] |
| 281 | |
| 282 | |
| 283 | def _hex_rgb(color: str) -> tuple[int, int, int]: |
| 284 | h = color.lstrip("#") |
| 285 | return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) |
| 286 | |
| 287 | |
| 288 | def _angled_gradient(c1: tuple[int, int, int], c2: tuple[int, int, int], angle: float) -> "Image.Image": |
| 289 | from PIL import Image, ImageDraw |
| 290 | |
| 291 | diag = int(math.hypot(WIDTH, HEIGHT)) + 4 |
| 292 | band = Image.new("RGB", (diag, diag)) |
| 293 | draw = ImageDraw.Draw(band) |
| 294 | last = diag - 1 or 1 |
| 295 | for y in range(diag): |
| 296 | draw.line((0, y, diag, y), fill=_lerp(c1, c2, y / last)) |
| 297 | band = band.rotate(-angle, resample=Image.Resampling.BILINEAR, expand=False) |
| 298 | cx, cy = band.size[0] // 2, band.size[1] // 2 |
| 299 | return band.crop((cx - WIDTH // 2, cy - HEIGHT // 2, cx - WIDTH // 2 + WIDTH, cy - HEIGHT // 2 + HEIGHT)) |
| 300 | |
| 301 | |
| 302 | def render_png(title: str) -> bytes: |
| 303 | """Zelfde indeling als de SVG, als PNG-bytes (voor LNReader / expo-image).""" |
| 304 | from io import BytesIO |
| 305 | |
| 306 | from PIL import Image, ImageDraw |
| 307 | |
| 308 | pal = palette(title) |
| 309 | font_size, lines = choose_layout(title) |
| 310 | c1, c2, c3 = _hex_rgb(pal["c1"]), _hex_rgb(pal["c2"]), _hex_rgb(pal["c3"]) |
| 311 | img = _angled_gradient(c1, c2, pal["angle"]).convert("RGBA") |
| 312 | overlay = Image.new("RGBA", (WIDTH, HEIGHT), (0, 0, 0, 0)) |
| 313 | od = ImageDraw.Draw(overlay) |
| 314 | variant = pal["variant"] |
| 315 | if variant == 1: |
| 316 | od.ellipse((WIDTH * 0.78 - 90, HEIGHT * 0.22 - 90, WIDTH * 0.78 + 90, HEIGHT * 0.22 + 90), fill=(*c3, 71)) |
| 317 | od.ellipse((WIDTH * 0.12 - 70, HEIGHT * 0.7 - 70, WIDTH * 0.12 + 70, HEIGHT * 0.7 + 70), fill=(*c1, 64)) |
| 318 | elif variant == 2: |
| 319 | step = 28 |
| 320 | for i in range(-HEIGHT, WIDTH + HEIGHT, step): |
| 321 | od.polygon( |
| 322 | [(i, 0), (i + 14, 0), (i + 14 - HEIGHT, HEIGHT), (i - HEIGHT, HEIGHT)], |
| 323 | fill=(*c3, 56), |
| 324 | ) |
| 325 | elif variant == 3: |
| 326 | od.ellipse((WIDTH * 0.3 - 110, HEIGHT * 0.32 - 110, WIDTH * 0.3 + 110, HEIGHT * 0.32 + 110), fill=(*c3, 56)) |
| 327 | od.ellipse((WIDTH * 0.85 - 95, HEIGHT * 0.55 - 95, WIDTH * 0.85 + 95, HEIGHT * 0.55 + 95), fill=(*c2, 71)) |
| 328 | elif variant == 4: |
| 329 | od.regular_polygon((120, 120, 90), 4, rotation=32, fill=(*c3, 46)) |
| 330 | od.regular_polygon((85, 225, 70), 4, rotation=-18, fill=(*c1, 56)) |
| 331 | elif variant == 5: |
| 332 | for i, y in enumerate(range(0, HEIGHT, 36)): |
| 333 | if i % 2 == 0: |
| 334 | od.rectangle((0, y, WIDTH, y + 18), fill=(*c3, 41)) |
| 335 | img = Image.alpha_composite(img, overlay) |
| 336 | |
| 337 | line_height = round(font_size * 1.22) |
| 338 | text_block = line_height * len(lines) |
| 339 | band_top = max(HEIGHT * 0.42, HEIGHT - TEXT_AREA_BOTTOM - text_block - BAND_PADDING * 2) |
| 340 | draw = ImageDraw.Draw(img) |
| 341 | draw.rectangle((0, int(band_top), WIDTH, HEIGHT), fill=(11, 16, 32, 140)) |
| 342 | font = _font(font_size) |
| 343 | first_baseline = band_top + BAND_PADDING + font_size |
| 344 | for i, line in enumerate(lines): |
| 345 | y = first_baseline + i * line_height |
| 346 | draw.text((WIDTH / 2 + 1, y + 1), line, font=font, fill=(11, 16, 32, 220), anchor="ms") |
| 347 | draw.text((WIDTH / 2, y), line, font=font, fill=(247, 244, 239, 255), anchor="ms") |
| 348 | |
| 349 | buf = BytesIO() |
| 350 | quantized = img.convert("RGB").quantize(colors=64, method=Image.Quantize.MEDIANCUT) |
| 351 | quantized.save(buf, format="PNG", optimize=True, compress_level=9) |
| 352 | return buf.getvalue() |
| 353 | |
| 354 | |
| 355 | def write_cover(dest_root: Path, title: str) -> str: |
| 356 | """Schrijf een coverbestand. PNG als Pillow beschikbaar is (voor LNReader), anders SVG.""" |
| 357 | dest_root = Path(dest_root) |
| 358 | svg_rel = cover_relpath(title) |
| 359 | try: |
| 360 | png_bytes = render_png(title) |
| 361 | rel = svg_rel[:-4] + ".png" |
| 362 | path = dest_root / rel |
| 363 | path.parent.mkdir(parents=True, exist_ok=True) |
| 364 | path.write_bytes(png_bytes) |
| 365 | return path.relative_to(dest_root).as_posix() |
| 366 | except Exception: |
| 367 | path = dest_root / svg_rel |
| 368 | path.parent.mkdir(parents=True, exist_ok=True) |
| 369 | path.write_text(render_svg(title), encoding="utf-8") |
| 370 | return path.relative_to(dest_root).as_posix() |