site-shots.py 19 KB

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