Nacre/tools/refshot.py

135 lines
5.3 KiB
Python
Executable file

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = "==3.12.*"
# dependencies = ["PyQt6==6.9.1", "PyQt6-WebEngine==6.9.0"]
# ///
"""Reference shot (D-030): load a URL in Chromium (QtWebEngine) and save the page as a PNG at a given size.
Usage: tools/refshot.py <url> <out.png> [--size 1280x720] [--wait 5] [--waitfor <js expr> [--timeout 60]]
[--js <expr>] [--scroll <px>] [--light] [--ua <string>]
--size the page's viewport in CSS pixels (match Nacre's page area, not its whole window)
--wait seconds to let the page run after it loaded (and after --waitfor gave true)
--waitfor poll this expression until it is truthy; a timeout is reported, the shot is still taken
--js run this after the wait; its result (JSON) is printed and written next to the shot as <out>.json
--scroll scroll the page by this many pixels before the shot
--light prefer-color-scheme light (default dark, like Nacre's default theme)
--ua user agent (default: QtWebEngine's, without the QtWebEngine token, so sites see plain Chrome)
Runs offscreen (no window) with an off-the-record profile (nothing kept) and software GL; uv makes a cached
venv with PyQt6 + PyQt6-WebEngine on first use, no system packages needed. Direct connections only (no proxy).
Exit 0 when the shot was written, 1 on load failure or timeout (the shot is still written when possible).
"""
import argparse
import json
import os
import re
import sys
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS",
"--disable-gpu --autoplay-policy=no-user-gesture-required --no-proxy-server")
os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1")
from PyQt6.QtCore import QSize, Qt, QTimer, QUrl # noqa: E402
from PyQt6.QtGui import QGuiApplication # noqa: E402
from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineSettings # noqa: E402
from PyQt6.QtWebEngineWidgets import QWebEngineView # noqa: E402
from PyQt6.QtWidgets import QApplication # noqa: E402
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("url")
ap.add_argument("out")
ap.add_argument("--size", default="1280x720")
ap.add_argument("--wait", type=float, default=5)
ap.add_argument("--waitfor")
ap.add_argument("--timeout", type=float, default=60)
ap.add_argument("--js")
ap.add_argument("--scroll", type=int, default=0)
ap.add_argument("--light", action="store_true")
ap.add_argument("--ua")
a = ap.parse_args()
w, h = (int(n) for n in a.size.lower().split("x"))
app = QApplication(sys.argv[:1])
hints = QGuiApplication.styleHints()
if hasattr(hints, "setColorScheme"):
hints.setColorScheme(Qt.ColorScheme.Light if a.light else Qt.ColorScheme.Dark)
profile = QWebEngineProfile(app) # no storage name: off the record, nothing written
profile.setHttpUserAgent(a.ua or re.sub(r" ?QtWebEngine/\S+", "", profile.httpUserAgent()))
page = QWebEnginePage(profile, app)
s = page.settings()
s.setAttribute(QWebEngineSettings.WebAttribute.PlaybackRequiresUserGesture, False)
s.setAttribute(QWebEngineSettings.WebAttribute.ScreenCaptureEnabled, False)
view = QWebEngineView()
view.setPage(page)
view.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen)
view.resize(QSize(w, h))
view.show()
state = {"rc": 0, "loaded": False}
def log(msg: str) -> None:
print(f"refshot: {msg}", flush=True)
def finish() -> None:
def shot(result=None) -> None:
if a.js is not None:
print(json.dumps(result), flush=True)
with open(os.path.splitext(a.out)[0] + ".json", "w") as f:
json.dump(result, f)
img = view.grab()
if img.isNull() or not img.save(a.out):
log("could not save the shot")
state["rc"] = 1
else:
log(f"wrote {a.out} ({img.width()}x{img.height()})")
app.quit()
def after_wait() -> None:
if a.js is not None:
page.runJavaScript(a.js, 0, shot)
else:
shot()
if a.scroll:
page.runJavaScript(f"window.scrollBy(0, {a.scroll})")
QTimer.singleShot(int(a.wait * 1000), after_wait)
def poll(left: float) -> None:
def got(v) -> None:
if v:
finish()
elif left <= 0:
log(f"waitfor timed out: {a.waitfor}")
state["rc"] = 1
finish()
else:
QTimer.singleShot(500, lambda: poll(left - 0.5))
page.runJavaScript(a.waitfor, 0, got)
def loaded(ok: bool) -> None:
if state["loaded"]:
return # later loads (in-page navigations, redirects) are part of the same visit
state["loaded"] = True
if not ok:
log("load failed")
state["rc"] = 1
if a.waitfor:
poll(a.timeout)
else:
finish()
page.loadFinished.connect(loaded)
# A page that never finishes loading is shot anyway.
QTimer.singleShot(int((a.timeout + 60) * 1000), lambda: (log("load timed out"), state.update(rc=1), loaded(True)))
page.load(QUrl(a.url))
app.exec()
return state["rc"]
if __name__ == "__main__":
sys.exit(main())