Skip to content

Hook to generate my own image #145

@ewjoachim

Description

@ewjoachim

Hello,

I'm willing to make a PR that lets people customize the social card.

Here is how I'd like to do it:

  • use Sphinx's event system (expecially emit_firstresult) to let people provide their own function that creates the image
  • separate the code that handle the location of the image from the code that handles the content of the image.
  • The code that handles the content of the image would be returning a BytesIO and dimensions. It would also recieve a callback function that, given a hash, checks whether a social card file already exists with that hash, so as to avoid re-generating images when it's not needed, but the specifics of the hash depend of the image function.
  • if a custom function is provided, no need to require that matplotlib is installed. This would just be used if we need to use the fallback generator
  • So that would mean the _social_card.py module wouldn't be imported at all if you provide the function. In fact, I'd rename it _social_card_matploplib.py to make it clear. The functions that are needed even when a custom hook is provided would either go in __init__.py or move to a new _social_card.py.

The API would then be:

# conf.py

from sphinxext import opengraph

def setup(app):
     app.connect("generate-social-card", generate_image)

def generate_image(
    app: Sphinx,
    settings: opengraph.SocialCardSettings,
    check_if_hash_exists: Callable[[str], bool],
) -> io.BytesIO | None:
   
   hash = ...  # compute hash based on image params
   if check_if_hash_exists(hash):
       raise opengraph.CardAlreadyExists

    # ... probably stuff with pillow or something.
    return io.BytesIO(...)

Would that be accepted ?
Thanks :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions