import-shots.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python3
  2. """Import the pictures the site shows from a folder of renders made by the RELEASED LYNX.exe (needs Pillow).
  3. python3 website/_src/import-shots.py RENDERS
  4. RENDERS holds what these commands wrote (all off-screen, no window is opened):
  5. LYNX.exe --artshot RENDERS\\art after editors with their own art (art/<name>-after-100.png)
  6. LYNX.exe --plugui RENDERS\\plugui effect editors (plugui/<Name>.png)
  7. LYNX.exe --flextrashot RENDERS\\extra a few more editors (extra/*.png)
  8. LYNX.exe --pluginthumbs RENDERS\\thumbs the plugin picker's pictures (thumbs/<key>.png, every plugin)
  9. LYNX.exe --showcase RENDERS\\snap\\Demo.lynx, then
  10. LYNX.exe --snapshot RENDERS\\snap\\s RENDERS\\snap\\Demo.lynx the windows and dialogs (snap/s-<name>.png)
  11. Writes assets/img/plugins/<id>.webp for every entry of catalog.json (its "img" names the render) with the sizes in
  12. catalog-img.json, and assets/img/wiki/<name>.webp for every /assets/img/wiki/<name>.webp a page or wiki article uses
  13. (from snap/s-<name>.png). A plugin whose render is missing gets no picture: its card shows a name plate.
  14. Sizes: a picture is never made larger than its render, and the pages never show one above its own size (build.py
  15. writes width and height from catalog-img.json and img-sizes.json). --artshot also writes each editor at twice the size
  16. (<name>-after-200.png): that becomes <id>@2x.webp, offered to dense screens through srcset. The other modes of the
  17. 0.1.25 program draw at 100% only, so their pictures have no @2x file. Small pictures are kept lossless, the rest at
  18. quality 90 (@2x: 84).
  19. The logo: where a render's program drew an older logo in the round button of a plugin's header, that button is
  20. painted over with assets/img/logo.png (the brand's mark) at the same place and size. LOGO (below) is the old button.
  21. (This importer belongs to the 0.1.25 pictures; scripts/site-shots.py --logo-was does the same for the current ones.)
  22. """
  23. import io
  24. import json
  25. import re
  26. import sys
  27. from pathlib import Path
  28. import numpy as np
  29. from PIL import Image
  30. SRC = Path(__file__).resolve().parent
  31. OUT = SRC.parent / "assets/img"
  32. # pictures that are a part of a snapshot: name -> (snapshot, box). The Plugin manager's sample rows name other makers'
  33. # plugins, so the site shows only the part below them.
  34. CROPS = {"plugin-manager-scan": ("plugin-manager", (0, 330, 980, 600))}
  35. LOGO = None # the logo 0.1.25 draws (RGBA, 256 px), read from <RENDERS>/logo-0.1.25.png
  36. BADGE = Image.open(OUT / "logo.png").convert("RGBA")
  37. _pts = {}
  38. def logo_points(d):
  39. """A grid of points inside the logo's disc at diameter d: (y, x, rgb)."""
  40. if d not in _pts:
  41. t = np.asarray(LOGO.resize((d, d), Image.LANCZOS), dtype=np.float32)
  42. n = max(6, min(10, d // 2))
  43. _pts[d] = [(y, x, t[y, x, :3]) for y in (int((i + .5) * d / n) for i in range(n)) for x in (int((j + .5) * d / n) for j in range(n))
  44. if (y - d / 2 + .5) ** 2 + (x - d / 2 + .5) ** 2 < (d * .36) ** 2]
  45. return _pts[d]
  46. def find_logo(im, sizes, region=None, limit=14.0):
  47. """Where 0.1.25 drew its logo button: (x, y, diameter) or None. Mean colour difference at the points decides."""
  48. if LOGO is None:
  49. return None
  50. x0, y0, x1, y1 = region or (0, 0, im.width, im.height)
  51. a = np.asarray(im.convert("RGB"), dtype=np.float32)[y0:y1, x0:x1]
  52. best = None
  53. for d in sizes:
  54. h, w = a.shape[0] - d + 1, a.shape[1] - d + 1
  55. if h < 1 or w < 1:
  56. break
  57. pts = logo_points(d)
  58. e = np.zeros((h, w), dtype=np.float32)
  59. for y, x, c in pts:
  60. e += np.abs(a[y:y + h, x:x + w] - c).sum(axis=2)
  61. i = np.unravel_index(e.argmin(), e.shape)
  62. v = float(e[i]) / (3 * len(pts))
  63. if best is None or v < best[3]:
  64. best = (x0 + int(i[1]), y0 + int(i[0]), d, v)
  65. return best[:3] if best and best[3] < limit else None
  66. def brand(im, scale=1, anywhere=False):
  67. """The picture with the brand's mark on the header's logo button (see the note at the top). -> (image, painted?)"""
  68. sizes = range(15 * scale, 24 * scale) if not anywhere else range(17 * scale, 20 * scale)
  69. hit = find_logo(im, sizes, None if anywhere else (0, 0, min(im.width, 420 * scale), min(im.height, 150 * scale)))
  70. if not hit:
  71. return im, False
  72. out = im.convert("RGBA")
  73. out.alpha_composite(BADGE.resize((hit[2], hit[2]), Image.LANCZOS), hit[:2])
  74. return out, True
  75. def save(im, dest, quality=90):
  76. """Lossless when that costs little (flat interface pictures often compress better that way), else at `quality`.
  77. The large @2x files (quality below 90) are not tried lossless: they would be several times the size."""
  78. im = im.convert("RGB")
  79. dest.parent.mkdir(parents=True, exist_ok=True)
  80. lossy, exact = io.BytesIO(), io.BytesIO()
  81. im.save(lossy, "WEBP", quality=quality, method=5)
  82. if quality >= 90:
  83. im.save(exact, "WEBP", lossless=True, method=4)
  84. data = exact.getvalue() if 0 < exact.tell() <= max(1.35 * lossy.tell(), 40000) else lossy.getvalue()
  85. if not dest.exists() or dest.read_bytes() != data:
  86. dest.write_bytes(data)
  87. return [im.width, im.height]
  88. def fit(im, maxw):
  89. return im if im.width <= maxw else im.resize((maxw, round(im.height * maxw / im.width)), Image.LANCZOS)
  90. def main():
  91. global LOGO
  92. if len(sys.argv) != 2:
  93. sys.exit(__doc__)
  94. renders = Path(sys.argv[1])
  95. if (renders / "logo-0.1.25.png").is_file():
  96. LOGO = Image.open(renders / "logo-0.1.25.png").convert("RGBA")
  97. dims, missing, painted = {}, [], []
  98. for p in json.loads((SRC / "catalog.json").read_text(encoding="utf-8")):
  99. f = renders / p.get("img", "")
  100. if not (p.get("img") and f.is_file()):
  101. missing.append(p["id"])
  102. continue
  103. one, hit = brand(Image.open(f))
  104. one = fit(one, 960)
  105. dims[p["id"]] = save(one, OUT / "plugins" / (p["id"] + ".webp"))
  106. big = f.with_name(f.name.replace("-100.png", "-200.png"))
  107. dense = OUT / "plugins" / (p["id"] + "@2x.webp")
  108. if big != f and big.is_file():
  109. two, hit2 = brand(Image.open(big), 2)
  110. hit = hit or hit2
  111. if two.size != (one.width * 2, one.height * 2):
  112. two = two.resize((one.width * 2, one.height * 2), Image.LANCZOS)
  113. save(two, dense, 84)
  114. dims[p["id"]].append(2)
  115. elif dense.exists():
  116. dense.unlink()
  117. if hit:
  118. painted.append(p["id"])
  119. (SRC / "catalog-img.json").write_text(json.dumps(dims, indent=0, sort_keys=True) + "\n", encoding="utf-8")
  120. used = set()
  121. for f in list((SRC / "wiki").glob("*.md")) + list((SRC / "pages").glob("*.html")):
  122. used |= set(re.findall(r"/assets/img/wiki/([\w.-]+)\.webp", f.read_text(encoding="utf-8")))
  123. nowiki = []
  124. for name in sorted(used):
  125. src, box = CROPS.get(name, (name, None))
  126. f = renders / "snap" / ("s-%s.png" % src)
  127. if f.is_file():
  128. im = Image.open(f)
  129. im, hit = brand(im.crop(box) if box else im, anywhere=True)
  130. save(fit(im, 1600), OUT / "wiki" / (name + ".webp"))
  131. if hit:
  132. painted.append("wiki/" + name)
  133. elif not (OUT / "wiki" / (name + ".webp")).is_file(): # (a few are made by hand from the running program)
  134. nowiki.append(name)
  135. sizes = {"/assets/img/" + str(f.relative_to(OUT)).replace("\\", "/"): list(Image.open(f).size)
  136. for f in sorted(OUT.rglob("*")) if f.suffix in (".webp", ".png") and f.parent.name != "plugins"}
  137. (SRC / "img-sizes.json").write_text(json.dumps(sizes, indent=0, sort_keys=True) + "\n", encoding="utf-8")
  138. print("import-shots: %d plugin pictures, %d with an @2x file (%d plugins without a picture: %s), %d wiki pictures (%d not found: %s)"
  139. % (len(dims), sum(1 for d in dims.values() if len(d) > 2), len(missing), ", ".join(missing) or "-", len(used) - len(nowiki), len(nowiki), ", ".join(nowiki) or "-"))
  140. print("import-shots: logo button painted in %d pictures: %s" % (len(painted), ", ".join(painted) or "-"))
  141. return 1 if nowiki else 0
  142. if __name__ == "__main__":
  143. sys.exit(main())