|
| 1 | +import hashlib |
| 2 | +import pathlib |
| 3 | +import subprocess |
| 4 | +import sqlite_utils |
| 5 | +import tempfile |
| 6 | + |
| 7 | +root = pathlib.Path(__file__).parent.resolve() |
| 8 | +TMP_PATH = pathlib.Path(tempfile.gettempdir()) |
| 9 | +SHOT_HASH_PATHS = [ |
| 10 | + (root / "templates" / "row.html"), |
| 11 | + (root / "templates" / "til_base.html"), |
| 12 | +] |
| 13 | + |
| 14 | + |
| 15 | +def png_for_path(path): |
| 16 | + page_html = str(TMP_PATH / "generate-screenshots-page.html") |
| 17 | + # Use datasette to generate HTML |
| 18 | + proc = subprocess.run(["datasette", ".", "--get", path], capture_output=True) |
| 19 | + open(page_html, "wb").write(proc.stdout) |
| 20 | + # Now use puppeteer screenshot to generate a PNG |
| 21 | + proc2 = subprocess.run( |
| 22 | + [ |
| 23 | + "puppeteer", |
| 24 | + "screenshot", |
| 25 | + page_html, |
| 26 | + "--viewport", |
| 27 | + "800x400", |
| 28 | + "--full-page=false", |
| 29 | + ], |
| 30 | + capture_output=True, |
| 31 | + ) |
| 32 | + png_bytes = proc2.stdout |
| 33 | + return png_bytes |
| 34 | + |
| 35 | + |
| 36 | +def generate_screenshots(root): |
| 37 | + db = sqlite_utils.Database(root / "tils.db") |
| 38 | + |
| 39 | + # The shot_hash incorporates a hash of all of row.html |
| 40 | + |
| 41 | + shot_html_hash = hashlib.md5() |
| 42 | + for filepath in SHOT_HASH_PATHS: |
| 43 | + shot_html_hash.update(filepath.read_text().encode("utf-8")) |
| 44 | + shot_html_hash = shot_html_hash.hexdigest() |
| 45 | + |
| 46 | + for row in db["til"].rows: |
| 47 | + path = row["path"] |
| 48 | + html = row["html"] |
| 49 | + shot_hash = hashlib.md5((shot_html_hash + html).encode("utf-8")).hexdigest() |
| 50 | + if shot_hash != row.get("shot_hash"): |
| 51 | + png = png_for_path("/{}/{}".format(row["topic"], row["slug"])) |
| 52 | + db["til"].update(path, {"shot": png, "shot_hash": shot_hash}, alter=True) |
| 53 | + print( |
| 54 | + "Got {} byte PNG for {} shot hash {}".format(len(png), path, shot_hash) |
| 55 | + ) |
| 56 | + else: |
| 57 | + print("Skipped {} with shot hash {}".format(path, shot_hash)) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + generate_screenshots(root) |
0 commit comments