| 1 |
"""Use playwright to build a gallery of website using this theme.""" |
| 2 |
|
| 3 |
from pathlib import Path |
| 4 |
from shutil import copy |
| 5 |
|
| 6 |
from playwright.sync_api import TimeoutError, sync_playwright |
| 7 |
from rich import print |
| 8 |
from rich.progress import track |
| 9 |
from yaml import safe_load |
| 10 |
|
| 11 |
|
| 12 |
def regenerate_gallery() -> None: |
| 13 |
"""Regenerate images of snapshots for our gallery. |
| 14 |
|
| 15 |
This function should only be triggered in RTD builds as it increases the build |
| 16 |
time by 30-60s. Developers can still execute this function from time to time to |
| 17 |
populate their local gallery images with updated files. |
| 18 |
""" |
| 19 |
# get the existing folders path |
| 20 |
_static_dir = Path(__file__).parents[1] / "_static" |
| 21 |
|
| 22 |
# create the static gallery folder where we'll put the gallery source files |
| 23 |
gallery_dir = _static_dir / "gallery" |
| 24 |
gallery_dir.mkdir(exist_ok=True) |
| 25 |
|
| 26 |
# load gallery data |
| 27 |
gallery_items = safe_load((_static_dir / "gallery.yaml").read_text()) |
| 28 |
image_404 = _static_dir / "404.png" |
| 29 |
|
| 30 |
with sync_playwright() as p: |
| 31 |
# Generate our browser to visit pages and generate images |
| 32 |
for ii in range(3): |
| 33 |
try: |
| 34 |
browser = p.chromium.launch() |
| 35 |
break |
| 36 |
except TimeoutError: |
| 37 |
print(f"Browser start timed out. Trying again (attempt {ii + 2}/3)") |
| 38 |
page = browser.new_page() |
| 39 |
|
| 40 |
for item in track(gallery_items, description="Generating screenshots..."): |
| 41 |
item["id"] = item["title"].lower().replace(" ", "_") |
| 42 |
screenshot = gallery_dir / f"{item['id']}.png" |
| 43 |
|
| 44 |
# Visit the page and take a screenshot |
| 45 |
for ii in range(3): |
| 46 |
try: |
| 47 |
page.goto(item["link"]) |
| 48 |
page.screenshot(path=screenshot) |
| 49 |
break |
| 50 |
except TimeoutError: |
| 51 |
print(f"Page visit start timed out for: {item['link']}") |
| 52 |
print(f"Trying again (attempt {ii + 2}/3)") |
| 53 |
|
| 54 |
# copy the 404 only if the screenshot file was not manually |
| 55 |
# generated by a maintainer |
| 56 |
if not screenshot.is_file(): |
| 57 |
print(f"Could not generate screenshot for {item['title']}, using 404.") |
| 58 |
copy(image_404, screenshot) |
| 59 |
|
| 60 |
# Clean up the browser since we no longer need it |
| 61 |
browser.close() |
| 62 |
print(f"Finished generating gallery images at: {gallery_dir}") |
| 63 |
|
| 64 |
|
| 65 |
if __name__ == "__main__": |
| 66 |
regenerate_gallery() |