| 1 |
"""Build a PNG card for each page meant for social media.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import hashlib |
| 6 |
from pathlib import Path |
| 7 |
from typing import TYPE_CHECKING |
| 8 |
|
| 9 |
import matplotlib as mpl |
| 10 |
import matplotlib.font_manager |
| 11 |
import matplotlib.image as mpimg |
| 12 |
from matplotlib import pyplot as plt |
| 13 |
from sphinx.util import logging |
| 14 |
|
| 15 |
if TYPE_CHECKING: |
| 16 |
from typing import TypeAlias |
| 17 |
|
| 18 |
from matplotlib.figure import Figure |
| 19 |
from matplotlib.text import Text |
| 20 |
from sphinx.environment import BuildEnvironment |
| 21 |
|
| 22 |
PltObjects: TypeAlias = tuple[Figure, Text, Text, Text, Text] |
| 23 |
|
| 24 |
mpl.use('agg') |
| 25 |
|
| 26 |
LOGGER = logging.getLogger(__name__) |
| 27 |
HERE = Path(__file__).parent |
| 28 |
MAX_CHAR_PAGE_TITLE = 75 |
| 29 |
MAX_CHAR_DESCRIPTION = 175 |
| 30 |
|
| 31 |
# Default configuration for this functionality |
| 32 |
DEFAULT_SOCIAL_CONFIG = { |
| 33 |
'enable': True, |
| 34 |
'site_url': True, |
| 35 |
'site_title': True, |
| 36 |
'page_title': True, |
| 37 |
'description': True, |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
# Default configuration for the figure style |
| 42 |
DEFAULT_KWARGS_FIG = { |
| 43 |
'enable': True, |
| 44 |
'site_url': True, |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
def create_social_card( |
| 49 |
config_social: dict[str, bool | str], |
| 50 |
site_name: str, |
| 51 |
page_title: str, |
| 52 |
description: str, |
| 53 |
url_text: str, |
| 54 |
page_path: str, |
| 55 |
*, |
| 56 |
srcdir: str | Path, |
| 57 |
outdir: str | Path, |
| 58 |
env: BuildEnvironment, |
| 59 |
html_logo: str | None = None, |
| 60 |
) -> Path: |
| 61 |
"""Create a social preview card according to page metadata. |
| 62 |
|
| 63 |
This uses page metadata and calls a render function to generate the image. |
| 64 |
It also passes configuration through to the rendering function. |
| 65 |
If Matplotlib objects are present in the `app` environment, it reuses them. |
| 66 |
""" |
| 67 |
# Add a hash to the image path based on metadata to bust caches |
| 68 |
# ref: https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/troubleshooting-cards#refreshing_images |
| 69 |
hash = hashlib.sha1( |
| 70 |
(site_name + page_title + description + str(config_social)).encode(), |
| 71 |
usedforsecurity=False, |
| 72 |
).hexdigest()[:8] |
| 73 |
|
| 74 |
# Define the file path we'll use for this image |
| 75 |
path_images_relative = Path('_images/social_previews') |
| 76 |
filename_image = f'summary_{page_path.replace("/", "_")}_{hash}.png' |
| 77 |
|
| 78 |
# Absolute path used to save the image |
| 79 |
path_images_absolute = Path(outdir) / path_images_relative |
| 80 |
path_images_absolute.mkdir(exist_ok=True, parents=True) |
| 81 |
path_image = path_images_absolute / filename_image |
| 82 |
|
| 83 |
# If the image already exists then we can just skip creating a new one. |
| 84 |
# This is because we hash the values of the text + images in the social card. |
| 85 |
# If the hash doesn't change, it means the output should be the same. |
| 86 |
if path_image.exists(): |
| 87 |
return path_images_relative / filename_image |
| 88 |
|
| 89 |
# These kwargs are used to generate the base figure image |
| 90 |
kwargs_fig: dict[str, str | Path | None] = {} |
| 91 |
|
| 92 |
# Large image to the top right |
| 93 |
if cs_image := config_social.get('image'): |
| 94 |
kwargs_fig['image'] = Path(srcdir) / cs_image |
| 95 |
elif html_logo: |
| 96 |
kwargs_fig['image'] = Path(srcdir) / html_logo |
| 97 |
|
| 98 |
# Mini image to the bottom right |
| 99 |
if cs_image_mini := config_social.get('image_mini'): |
| 100 |
kwargs_fig['image_mini'] = Path(srcdir) / cs_image_mini |
| 101 |
else: |
| 102 |
kwargs_fig['image_mini'] = ( |
| 103 |
Path(__file__).parent / '_static/sphinx-logo-shadow.png' |
| 104 |
) |
| 105 |
|
| 106 |
# Validation on the images |
| 107 |
for img in ['image_mini', 'image']: |
| 108 |
impath = kwargs_fig.get(img) |
| 109 |
if not impath: |
| 110 |
continue |
| 111 |
|
| 112 |
# If image is an SVG replace it with None |
| 113 |
if impath.suffix.lower() == '.svg': |
| 114 |
LOGGER.warning('[Social card] %s cannot be an SVG image, skipping...', img) |
| 115 |
kwargs_fig[img] = None |
| 116 |
|
| 117 |
# If image doesn't exist, throw a warning and replace with none |
| 118 |
if not impath.exists(): |
| 119 |
LOGGER.warning("[Social card]: %s file doesn't exist, skipping...", img) |
| 120 |
kwargs_fig[img] = None |
| 121 |
|
| 122 |
# These are passed directly from the user configuration to our plotting function |
| 123 |
pass_through_config = ('text_color', 'line_color', 'background_color', 'font') |
| 124 |
for config in pass_through_config: |
| 125 |
if cs_config := config_social.get(config): |
| 126 |
kwargs_fig[config] = cs_config |
| 127 |
|
| 128 |
# Generate the image and store the matplotlib objects so that we can re-use them |
| 129 |
try: |
| 130 |
plt_objects = env.ogp_social_card_plt_objects |
| 131 |
except AttributeError: |
| 132 |
# If objects is None it means this is the first time plotting. |
| 133 |
# Create the figure objects and return them so that we re-use them later. |
| 134 |
plt_objects = create_social_card_objects(**kwargs_fig) |
| 135 |
plt_objects = render_social_card( |
| 136 |
path_image, |
| 137 |
site_name, |
| 138 |
page_title, |
| 139 |
description, |
| 140 |
url_text, |
| 141 |
plt_objects, |
| 142 |
) |
| 143 |
env.ogp_social_card_plt_objects = plt_objects |
| 144 |
|
| 145 |
# Path relative to build folder will be what we use for linking the URL |
| 146 |
return path_images_relative / filename_image |
| 147 |
|
| 148 |
|
| 149 |
def render_social_card( |
| 150 |
path: Path, |
| 151 |
site_title: str, |
| 152 |
page_title: str, |
| 153 |
description: str, |
| 154 |
siteurl: str, |
| 155 |
plt_objects: PltObjects, |
| 156 |
) -> PltObjects: |
| 157 |
"""Render a social preview card with Matplotlib and write to disk.""" |
| 158 |
fig, txt_site_title, txt_page_title, txt_description, txt_url = plt_objects |
| 159 |
|
| 160 |
# Update the matplotlib text objects with new text from this page |
| 161 |
txt_site_title.set_text(site_title) |
| 162 |
txt_page_title.set_text(page_title) |
| 163 |
txt_description.set_text(description) |
| 164 |
txt_url.set_text(siteurl) |
| 165 |
|
| 166 |
# Save the image |
| 167 |
fig.savefig(path, facecolor=None) |
| 168 |
return fig, txt_site_title, txt_page_title, txt_description, txt_url |
| 169 |
|
| 170 |
|
| 171 |
def create_social_card_objects( |
| 172 |
image: Path | None = None, |
| 173 |
image_mini: Path | None = None, |
| 174 |
page_title_color: str = '#2f363d', |
| 175 |
description_color: str = '#585e63', |
| 176 |
site_title_color: str = '#585e63', |
| 177 |
site_url_color: str = '#2f363d', |
| 178 |
background_color: str = 'white', |
| 179 |
line_color: str = '#5A626B', |
| 180 |
font: str | None = None, |
| 181 |
) -> PltObjects: |
| 182 |
"""Create the Matplotlib objects for the first time.""" |
| 183 |
# If no font specified, load the Roboto Flex font as a fallback |
| 184 |
if font is None: |
| 185 |
path_font = Path(__file__).parent / '_static/Roboto-Flex.ttf' |
| 186 |
roboto_font = matplotlib.font_manager.FontEntry( |
| 187 |
fname=str(path_font), name='Roboto Flex' |
| 188 |
) |
| 189 |
matplotlib.font_manager.fontManager.addfont(path_font) |
| 190 |
font = roboto_font.name |
| 191 |
|
| 192 |
# Because Matplotlib doesn't let you specify figures in pixels, only inches |
| 193 |
# This `multiple` results in a scale of about 1146px by 600px |
| 194 |
# Which is roughly the recommended size for OpenGraph images |
| 195 |
# ref: https://opengraph.xyz |
| 196 |
ratio = 1200 / 628 |
| 197 |
multiple = 6 |
| 198 |
fig = plt.figure(figsize=(ratio * multiple, multiple)) |
| 199 |
fig.set_facecolor(background_color) |
| 200 |
|
| 201 |
# Text axis |
| 202 |
axtext = fig.add_axes((0, 0, 1, 1)) |
| 203 |
|
| 204 |
# Image axis |
| 205 |
ax_x, ax_y, ax_w, ax_h = (0.65, 0.65, 0.3, 0.3) |
| 206 |
axim_logo = fig.add_axes((ax_x, ax_y, ax_w, ax_h), anchor='NE') |
| 207 |
|
| 208 |
# Image mini axis |
| 209 |
ax_x, ax_y, ax_w, ax_h = (0.82, 0.1, 0.1, 0.1) |
| 210 |
axim_mini = fig.add_axes((ax_x, ax_y, ax_w, ax_h), anchor='NE') |
| 211 |
|
| 212 |
# Line at the bottom axis |
| 213 |
axline = fig.add_axes((-0.1, -0.04, 1.2, 0.1)) |
| 214 |
|
| 215 |
# Axes configuration |
| 216 |
left_margin = 0.05 |
| 217 |
with plt.rc_context({'font.family': font}): |
| 218 |
# Site title |
| 219 |
# Smaller font, just above page title |
| 220 |
site_title_y_offset = 0.87 |
| 221 |
txt_site = axtext.text( |
| 222 |
left_margin, |
| 223 |
site_title_y_offset, |
| 224 |
'Test site title', |
| 225 |
{'size': 24}, |
| 226 |
ha='left', |
| 227 |
va='top', |
| 228 |
wrap=True, |
| 229 |
c=site_title_color, |
| 230 |
) |
| 231 |
|
| 232 |
# Page title |
| 233 |
# A larger font for more visibility |
| 234 |
page_title_y_offset = 0.77 |
| 235 |
|
| 236 |
txt_page = axtext.text( |
| 237 |
left_margin, |
| 238 |
page_title_y_offset, |
| 239 |
'Test page title, a bit longer to demo', |
| 240 |
{'size': 46, 'color': 'k', 'fontweight': 'bold'}, |
| 241 |
ha='left', |
| 242 |
va='top', |
| 243 |
wrap=True, |
| 244 |
c=page_title_color, |
| 245 |
) |
| 246 |
|
| 247 |
txt_page._get_wrap_line_width = _set_page_title_line_width # NoQA: SLF001 |
| 248 |
|
| 249 |
# description |
| 250 |
# Just below site title, smallest font and many lines. |
| 251 |
# Our target length is 160 characters, so it should be |
| 252 |
# two lines at full width with some room to spare at this length. |
| 253 |
description_y_offset = 0.2 |
| 254 |
txt_description = axtext.text( |
| 255 |
left_margin, |
| 256 |
description_y_offset, |
| 257 |
( |
| 258 |
'A longer description that we use to ,' |
| 259 |
'show off what the descriptions look like.' |
| 260 |
), |
| 261 |
{'size': 17}, |
| 262 |
ha='left', |
| 263 |
va='bottom', |
| 264 |
wrap=True, |
| 265 |
c=description_color, |
| 266 |
) |
| 267 |
txt_description._get_wrap_line_width = _set_description_line_width # NoQA: SLF001 |
| 268 |
|
| 269 |
# url |
| 270 |
# Aligned to the left of the mini image |
| 271 |
url_y_axis_ofset = 0.12 |
| 272 |
txt_url = axtext.text( |
| 273 |
left_margin, |
| 274 |
url_y_axis_ofset, |
| 275 |
'testurl.org', |
| 276 |
{'size': 22}, |
| 277 |
ha='left', |
| 278 |
va='bottom', |
| 279 |
fontweight='bold', |
| 280 |
c=site_url_color, |
| 281 |
) |
| 282 |
|
| 283 |
if isinstance(image_mini, Path): |
| 284 |
img = mpimg.imread(image_mini) |
| 285 |
axim_mini.imshow(img) |
| 286 |
|
| 287 |
# Put the logo in the top right if it exists |
| 288 |
if isinstance(image, Path): |
| 289 |
img = mpimg.imread(image) |
| 290 |
yw, xw = img.shape[:2] |
| 291 |
|
| 292 |
# Axis is square and width is longest image axis |
| 293 |
longest = max([yw, xw]) |
| 294 |
axim_logo.set_xlim([0, longest]) |
| 295 |
axim_logo.set_ylim([longest, 0]) |
| 296 |
|
| 297 |
# Center it on the non-long axis |
| 298 |
xdiff = (longest - xw) / 2 |
| 299 |
ydiff = (longest - yw) / 2 |
| 300 |
axim_logo.imshow(img, extent=[xdiff, xw + xdiff, yw + ydiff, ydiff]) |
| 301 |
|
| 302 |
# Put a colored line at the bottom of the figure |
| 303 |
axline.hlines(0, 0, 1, lw=25, color=line_color) |
| 304 |
|
| 305 |
# Remove the ticks and borders from all axes for a clean look |
| 306 |
for ax in fig.axes: |
| 307 |
ax.set_axis_off() |
| 308 |
return fig, txt_site, txt_page, txt_description, txt_url |
| 309 |
|
| 310 |
|
| 311 |
# These functions are used when creating social card objects to set MPL values. |
| 312 |
# They must be defined here otherwise Sphinx errors when trying to pickle them. |
| 313 |
# They are dependent on the `multiple` variable defined when the figure is created. |
| 314 |
# Because they are depending on the figure size and renderer used to generate them. |
| 315 |
def _set_page_title_line_width() -> int: |
| 316 |
return 825 |
| 317 |
|
| 318 |
|
| 319 |
def _set_description_line_width() -> int: |
| 320 |
return 1000 |