site-shots.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/usr/bin/env python3
  2. """Turn the renders of scripts/site-shots.sh into the pictures the website and the README use, at 1x and 2x (Pillow).
  3. python3 scripts/site-shots.py RENDERS [--site website] [--docs docs/img] [--logo-was LOGO.png] [--dry-run]
  4. RENDERS is what site-shots.sh wrote: x1/ and x2/ (one folder per pixel scale, the same file names in each: snap/,
  5. snap1600/, grid/, grid1600/, plugui/, extra/, thumbs/, dance/) and art/ (--artshot draws 100 % and 200 % itself).
  6. Writes (names as website/_src/build.py reads them):
  7. website/assets/img/<name>.webp + <name>@2x.webp the Home / Features pictures (TOP below)
  8. website/assets/img/plugins/<id>.webp + <id>@2x.webp every entry of _src/catalog.json (its "img" names the render)
  9. website/assets/img/wiki/<name>.webp + <name>@2x.webp every /assets/img/wiki/<name>.webp a page or article uses
  10. website/_src/catalog-img.json, website/_src/img-sizes.json the 1x sizes (build.py writes width/height from them;
  11. a catalog entry [w, h, 2] has an @2x file for srcset)
  12. docs/img/<name>.png + <name>@2x.png the README's pictures (README_PICTURES below)
  13. docs/img/social-preview.png the GitHub social preview (scripts/social-preview.py: its text
  14. lives there) around the hero's render
  15. store/screenshots/<name>.png the Store screenshots 01-04 (STORE below), 1x
  16. website/assets/media/poster.jpg the Features video's poster, 1280 x 720 from the 2x hero
  17. The @2x file is always exactly twice the 1x file's size and is drawn by the program at 2x (never an upscale). A 2x
  18. render missing for a picture: no @2x file is written (and an old one is removed), the table says so.
  19. Pictures larger than the page shows are fitted (plugins 960 px wide, wiki 1600 px) with the same factor at both scales.
  20. WebP: lossless when that costs little (flat interface pictures), else quality 92 (1x) / 88 (2x). Prints a table.
  21. --logo-was LOGO.png: the logo the build that made the renders draws (its src/ui/LogoData.h image), for renders made
  22. before a logo change. Wherever that build drew its logo button (plugin headers), the button is repainted with the
  23. brand's mark (the logo by w3teal without its app-icon tile, rendered by tools/make_logo.py from resources/brand; up to
  24. 32 px its small-size form, below 24 px without the pepper stem): a dark disc over the old button and the mark on it,
  25. its ears inside the picture, as the program draws it (src/ui/PluginSkin.cpp brandMark). Leave it out for renders of a build that draws the current logo.
  26. """
  27. import argparse
  28. import io
  29. import json
  30. import re
  31. import sys
  32. from pathlib import Path
  33. from PIL import Image, ImageDraw
  34. # Home / Features pictures: name -> (render, crop box at 1x or None)
  35. TOP = {
  36. "hero": ("snap/s-desktop-all.png", None), # Channel Rack, Piano Roll, Playlist and Mixer (the page's alt text)
  37. "playlist": ("snap/s-playlist-fit.png", None), # (round 190nr: the song zoomed to fit; --snapshot's -playlist-fit.png)
  38. "pianoroll": ("snap/s-pianoroll.png", None),
  39. "mixer": ("snap/s-mixer.png", None),
  40. "rack": ("snap/s-rack.png", (0, 0, 1074, 420)),
  41. "automation": ("snap/s-automation.png", None),
  42. "synth": ("snap/s-synth.png", None),
  43. "eq": ("art/facet-eq-after", None),
  44. "cliplaunch": ("grid/g-both.png", None),
  45. }
  46. # the README's pictures (docs/img/<name>.png): the 1600 x 900 window for the wide ones, as the README had them
  47. README_PICTURES = {
  48. "workspace": ("snap1600/s-desktop-all.png", None), # the same four windows as the hero (the README's caption)
  49. # (the part with the song: since 0.1.30 the Playlist opens at FL's default zoom, the demo fills its first fifth)
  50. "playlist": ("snap/s-playlist.png", (0, 75, 1000, 482)),
  51. "channel-rack": ("snap/s-rack.png", (0, 0, 1074, 420)),
  52. "piano-roll": ("snap1600/s-pianoroll.png", None),
  53. "mixer": ("snap1600/s-mixer.png", None),
  54. "synth": ("snap/s-synth.png", None),
  55. "eq": ("art/facet-eq-after", None),
  56. "automation": ("snap/s-automation.png", None),
  57. "clip-launch": ("grid1600/g-both.png", None),
  58. }
  59. # the Microsoft Store listing's screenshots (store/screenshots/<name>.png, 1920 x 1080, 1x only); 05-instruments-effects is
  60. # put together by hand (Channel Rack + a synth + Parametric EQ) and is not written here
  61. STORE = {
  62. "01-workspace": "snap/s-desktop-all.png",
  63. "02-playlist": "snap/s-playlist-fit.png",
  64. "03-piano-roll": "snap/s-pianoroll-narrow150.png",
  65. "04-mixer": "snap/s-mixer.png",
  66. }
  67. # the Features page's video poster (website/assets/media/poster.jpg, 1280 x 720) and the GitHub social preview
  68. # (docs/img/social-preview.png, drawn by scripts/social-preview.py around it): both from the hero's render
  69. POSTER = "snap/s-desktop-all.png"
  70. # wiki pictures that are a part of a snapshot: name -> (snapshot, box at 1x). The Plugin manager's sample rows name
  71. # other makers' plugins, so the site shows only the part below them (same as website/_src/import-shots.py).
  72. CROPS = {"plugin-manager-scan": ("plugin-manager", (0, 330, 980, 600))}
  73. def render(root, ref, scale):
  74. """The file of render `ref` at `scale` (1 or 2), or None. art/<name>-after: --artshot's own -100 / -200 files."""
  75. if ref.startswith("art/"):
  76. name = re.sub(r"-(100|200)\.png$", "", ref)
  77. f = root / ("%s-%d.png" % (name, 100 * scale))
  78. else:
  79. f = root / ("x%d" % scale) / ref
  80. return f if f.is_file() else None
  81. class LogoPainter:
  82. """Finds the old logo button in a render and paints the brand's button over it (see --logo-was)."""
  83. DARK = (14, 15, 19) # the disc under the mark (src/ui/PluginSkin.cpp brandMark)
  84. def __init__(self, old):
  85. import numpy as np
  86. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools"))
  87. import make_logo # the brand's pictures, from resources/brand/*.svg
  88. self.np = np
  89. self.logo = make_logo.Logo()
  90. self.old = Image.open(old).convert("RGBA")
  91. self.disc = (0.5, 0.5, 184.0 / 512.0) # the mark's ring in its 512-unit frame (centre, radius)
  92. self.pts = {}
  93. self.count = 0
  94. def points(self, d):
  95. """A grid of points inside the old logo at diameter d: (y, x, rgb)."""
  96. if d not in self.pts:
  97. np = self.np
  98. t = np.asarray(self.old.resize((d, d), Image.LANCZOS), dtype=np.float32)
  99. n = max(6, min(10, d // 2))
  100. self.pts[d] = [(y, x, t[y, x, :3]) for y in (int((i + .5) * d / n) for i in range(n))
  101. for x in (int((j + .5) * d / n) for j in range(n))
  102. if (y - d / 2 + .5) ** 2 + (x - d / 2 + .5) ** 2 < (d * .36) ** 2]
  103. return self.pts[d]
  104. def find(self, a, sizes, limit=14.0):
  105. """Best (x, y, d) of the old logo in the array a, or None."""
  106. np = self.np
  107. best = None
  108. for d in sizes:
  109. h, w = a.shape[0] - d + 1, a.shape[1] - d + 1
  110. if h < 1 or w < 1:
  111. continue
  112. pts = self.points(d)
  113. e = np.zeros((h, w), dtype=np.float32)
  114. for y, x, c in pts:
  115. e += np.abs(a[y:y + h, x:x + w] - c).sum(axis=2)
  116. i = np.unravel_index(e.argmin(), e.shape)
  117. v = float(e[i]) / (3 * len(pts))
  118. if best is None or v < best[3]:
  119. best = (int(i[1]), int(i[0]), d, v)
  120. return best[:3] if best and best[3] < limit else None
  121. def paint(self, im, scale):
  122. """im with every old logo button repainted (sizes: the 18 and 20 px header buttons, Strike's 40 px plate)."""
  123. np = self.np
  124. rgb = np.asarray(im.convert("RGB"), dtype=np.float32)
  125. # the old logo is a red pepper with a green stem: search only around pixels of that green
  126. g = (rgb[..., 1] > rgb[..., 0] + 40) & (rgb[..., 1] > rgb[..., 2] + 40) & (rgb[..., 1] > 90)
  127. ys, xs = np.nonzero(g)
  128. if len(xs) == 0:
  129. return im, 0
  130. sizes = sorted({v * scale + k for v in (18, 20, 40) for k in (-1, 0, 1)})
  131. cell, span = 48 * scale, 48 * scale
  132. cells = sorted({(int(y) // cell, int(x) // cell) for y, x in zip(ys, xs)})
  133. hits = []
  134. for cy, cx in cells:
  135. y0, x0 = max(0, cy * cell - span), max(0, cx * cell - span)
  136. y1, x1 = min(rgb.shape[0], (cy + 1) * cell + span), min(rgb.shape[1], (cx + 1) * cell + span)
  137. hit = self.find(rgb[y0:y1, x0:x1], sizes)
  138. if hit:
  139. hit = (hit[0] + x0, hit[1] + y0, hit[2])
  140. if all(abs(hit[0] - h[0]) > 4 or abs(hit[1] - h[1]) > 4 for h in hits):
  141. hits.append(hit)
  142. if not hits:
  143. return im, 0
  144. out = im.convert("RGBA")
  145. for x, y, d in hits:
  146. self.draw(out, x + d / 2.0, y + d / 2.0, d, scale)
  147. self.count += len(hits)
  148. return out.convert(im.mode if im.mode in ("RGB", "RGBA") else "RGB"), len(hits)
  149. def draw(self, out, cx, cy, d, scale):
  150. """The brand's button over an old one of diameter d centred at (cx, cy) in the RGBA picture out."""
  151. r = d / 2.0 + 1.5 * scale # over the old button's dark edge and red ring
  152. fx, fy, fr = self.disc
  153. side = min(r / fr, cy / fy) # (the ears stay inside the picture, as the program keeps them in the header)
  154. r0, r = r, side * fr
  155. k = 4 # the disc drawn 4x and scaled down (smooth edge)
  156. rd = max(r0, r + scale) # the dark disc: over the old button, at least 1 px beyond the mark
  157. box = (int(cx - rd) - 2, int(cy - rd) - 2, int(cx + rd) + 3, int(cy + rd) + 3)
  158. w, h = box[2] - box[0], box[3] - box[1]
  159. mask = Image.new("L", (w * k, h * k), 0)
  160. ImageDraw.Draw(mask).ellipse(((cx - rd - box[0]) * k, (cy - rd - box[1]) * k, (cx + rd - box[0]) * k, (cy + rd - box[1]) * k), fill=255)
  161. disc = Image.new("RGBA", (w, h), self.DARK + (255,))
  162. disc.putalpha(mask.resize((w, h), Image.LANCZOS))
  163. out.alpha_composite(disc, box[:2])
  164. px = max(1, round(side))
  165. mark = self.logo.mark(px, small=side <= 32)
  166. out.alpha_composite(mark, (round(cx - fx * side), round(cy - fy * side)))
  167. def webp(im, quality):
  168. im = im.convert("RGB")
  169. lossy, exact = io.BytesIO(), io.BytesIO()
  170. im.save(lossy, "WEBP", quality=quality, method=6)
  171. im.save(exact, "WEBP", lossless=True, method=4)
  172. return exact.getvalue() if exact.tell() <= 1.35 * lossy.tell() else lossy.getvalue()
  173. def png(im):
  174. out = io.BytesIO()
  175. im.convert("RGB").save(out, "PNG", optimize=True)
  176. return out.getvalue()
  177. class Writer:
  178. def __init__(self, dry, painter=None):
  179. self.dry, self.rows, self.painter, self.painted = dry, [], painter, []
  180. def put(self, dest, data, size, source):
  181. if not self.dry:
  182. dest.parent.mkdir(parents=True, exist_ok=True)
  183. if not dest.exists() or dest.read_bytes() != data:
  184. dest.write_bytes(data)
  185. self.rows.append((str(dest), "%dx%d" % size, len(data), source))
  186. def drop(self, dest):
  187. if dest.exists() and not self.dry:
  188. dest.unlink()
  189. def pair(self, root, ref, box, dest1, dest2, maxw=None, fmt="webp"):
  190. """One picture at 1x and 2x. Returns the 1x size [w, h] (+ [2] when the @2x file exists), or None."""
  191. f1, f2 = render(root, ref, 1), render(root, ref, 2)
  192. if f1 is None:
  193. self.rows.append((str(dest1), "-", 0, "MISSING " + ref))
  194. return None
  195. one = Image.open(f1)
  196. if box:
  197. one = one.crop(box)
  198. if self.painter:
  199. one, n = self.painter.paint(one, 1)
  200. if n:
  201. self.painted.append(str(dest1))
  202. k = 1.0 if not maxw or one.width <= maxw else maxw / one.width
  203. if k != 1.0:
  204. one = one.resize((maxw, round(one.height * k)), Image.LANCZOS)
  205. enc = (lambda im, q: webp(im, q)) if fmt == "webp" else (lambda im, q: png(im))
  206. self.put(dest1, enc(one, 92), one.size, str(f1))
  207. dims = [one.width, one.height]
  208. if f2 is None:
  209. self.drop(dest2)
  210. self.rows.append((str(dest2), "-", 0, "no 2x render of " + ref))
  211. return dims
  212. two = Image.open(f2)
  213. if box:
  214. two = two.crop(tuple(2 * v for v in box))
  215. if self.painter:
  216. two, n = self.painter.paint(two, 2)
  217. if n:
  218. self.painted.append(str(dest2))
  219. want = (2 * one.width, 2 * one.height)
  220. if two.size != want:
  221. # (a fitted picture, or a render a pixel off from rounding: scaled to exactly twice the 1x file)
  222. if abs(two.width - want[0]) > max(2, want[0] // 100) and k == 1.0:
  223. self.rows.append((str(dest2), "%dx%d" % two.size, 0, "SIZE MISMATCH, expected %dx%d: not written" % want))
  224. self.drop(dest2)
  225. return dims
  226. two = two.resize(want, Image.LANCZOS)
  227. self.put(dest2, enc(two, 88), two.size, str(f2))
  228. return dims + [2]
  229. def main():
  230. ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  231. ap.add_argument("renders")
  232. ap.add_argument("--site", default="website")
  233. ap.add_argument("--docs", default="docs/img")
  234. ap.add_argument("--store", help="the Store screenshots folder (default: store/screenshots beside the site folder)")
  235. ap.add_argument("--logo-was", help="the logo the renders' build draws (repaint its button with the brand's mark)")
  236. ap.add_argument("--dry-run", action="store_true")
  237. a = ap.parse_args()
  238. root, site, docs = Path(a.renders), Path(a.site), Path(a.docs)
  239. img, src = site / "assets/img", site / "_src"
  240. w = Writer(a.dry_run, LogoPainter(a.logo_was) if a.logo_was else None)
  241. sizes = {}
  242. for name, (ref, box) in TOP.items():
  243. d = w.pair(root, ref, box, img / (name + ".webp"), img / (name + "@2x.webp"))
  244. if d:
  245. sizes["/assets/img/%s.webp" % name] = d[:2]
  246. for name, (ref, box) in README_PICTURES.items():
  247. w.pair(root, ref, box, docs / (name + ".png"), docs / (name + "@2x.png"), fmt="png")
  248. # the Store screenshots (1x), the video poster and the social preview, from the hero's render
  249. store = Path(a.store) if a.store else site.resolve().parent / "store" / "screenshots"
  250. for name, ref in STORE.items():
  251. f1 = render(root, ref, 1)
  252. if f1 is None:
  253. w.rows.append((str(store / (name + ".png")), "-", 0, "MISSING " + ref))
  254. continue
  255. one = Image.open(f1)
  256. if w.painter:
  257. one, _ = w.painter.paint(one, 1)
  258. w.put(store / (name + ".png"), png(one), one.size, str(f1))
  259. two = render(root, POSTER, 2)
  260. big = two or render(root, POSTER, 1)
  261. if big is None:
  262. w.rows.append((str(site / "assets/media/poster.jpg"), "-", 0, "MISSING " + POSTER))
  263. else:
  264. im = Image.open(big)
  265. if w.painter:
  266. im, _ = w.painter.paint(im, 2 if two else 1)
  267. out = io.BytesIO()
  268. im.convert("RGB").resize((1280, 720), Image.LANCZOS).save(out, "JPEG", quality=88, optimize=True, progressive=True)
  269. w.put(site / "assets/media/poster.jpg", out.getvalue(), (1280, 720), str(big))
  270. social = docs / "social-preview.png"
  271. tool = Path(__file__).resolve().parent / "social-preview.py"
  272. tmp = Path(str(social) + ".new.png")
  273. import subprocess
  274. done = subprocess.run([sys.executable, str(tool), "--window", str(big), "--out", str(tmp)], capture_output=True, text=True)
  275. if done.returncode != 0 or not tmp.is_file():
  276. w.rows.append((str(social), "-", 0, "MISSING: social-preview.py failed: " + (done.stderr or done.stdout).strip()))
  277. else:
  278. data = tmp.read_bytes()
  279. tmp.unlink()
  280. w.put(social, data, Image.open(io.BytesIO(data)).size, "social-preview.py + " + str(big))
  281. catalog = src / "catalog.json"
  282. if catalog.is_file():
  283. dims = {}
  284. for p in json.loads(catalog.read_text(encoding="utf-8")):
  285. if not p.get("img"):
  286. continue
  287. d = w.pair(root, p["img"], None, img / "plugins" / (p["id"] + ".webp"), img / "plugins" / (p["id"] + "@2x.webp"), maxw=960)
  288. if d:
  289. dims[p["id"]] = d
  290. if not a.dry_run:
  291. (src / "catalog-img.json").write_text(json.dumps(dims, indent=0, sort_keys=True) + "\n", encoding="utf-8")
  292. used = set()
  293. for f in list((src / "wiki").glob("*.md")) + list((src / "pages").glob("*.html")):
  294. used |= set(re.findall(r"/assets/img/wiki/([\w.-]+)\.webp", f.read_text(encoding="utf-8")))
  295. for name in sorted(used):
  296. snap, box = CROPS.get(name, (name, None))
  297. if render(root, "snap/s-%s.png" % snap, 1) is None and (img / "wiki" / (name + ".webp")).is_file():
  298. w.rows.append((str(img / "wiki" / (name + ".webp")), "-", 0, "kept: no render (a picture made by hand)"))
  299. continue
  300. d = w.pair(root, "snap/s-%s.png" % snap, box, img / "wiki" / (name + ".webp"), img / "wiki" / (name + "@2x.webp"), maxw=1600)
  301. if d:
  302. sizes["/assets/img/wiki/%s.webp" % name] = d[:2]
  303. old = src / "img-sizes.json"
  304. if old.is_file():
  305. merged = json.loads(old.read_text(encoding="utf-8"))
  306. merged.update(sizes)
  307. sizes = merged
  308. if not a.dry_run:
  309. old.write_text(json.dumps(sizes, indent=0, sort_keys=True) + "\n", encoding="utf-8")
  310. else:
  311. print("note: %s not found (the site generator's data): only the Home pictures and the README's were written" % catalog)
  312. width = max(len(r[0]) for r in w.rows) if w.rows else 10
  313. print("%-*s %-11s %9s %s" % (width, "file", "pixels", "bytes", "from"))
  314. for f, px, n, s in w.rows:
  315. print("%-*s %-11s %9s %s" % (width, f, px, n or "-", s))
  316. if w.painter:
  317. print("site-shots: logo button repainted %d times in %d files" % (w.painter.count, len(w.painted)))
  318. written = [r for r in w.rows if r[2]]
  319. problems = [r for r in w.rows if not r[2]]
  320. print("site-shots: %d files %s, %d with a note (missing render or no 2x)%s"
  321. % (len(written), "checked (dry run)" if a.dry_run else "written", len(problems), "" if problems else ""))
  322. return 1 if any(r[3].startswith(("MISSING", "SIZE")) for r in problems) else 0
  323. if __name__ == "__main__":
  324. sys.exit(main())