Skip to content

Commit ab67a5e

Browse files
committed
Address review
1 parent db310b2 commit ab67a5e

5 files changed

Lines changed: 45 additions & 110 deletions

File tree

‎plotly/io/_base_renderers.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -820,11 +820,10 @@ def to_mimebundle(self, fig_dict):
820820
class SphinxGalleryPngRenderer(ExternalRenderer):
821821
"""Renderer used together with the sphinx-gallery image scraper.
822822
823-
Instead of displaying the figure, this renderer queues it in
824-
``plotly.io._base_renderers.sphinx_gallery_figures``;
825-
:func:`plotly.io._sg_scraper.plotly_sg_scraper` then writes each queued
826-
figure to the gallery's image directory, both as an interactive HTML file
827-
and as a static image used for the gallery thumbnail.
823+
Rather than displaying the figure, this renderer queues it for
824+
``plotly.io.sg_scraper.plotly_sg_scraper``, which embeds it in the example
825+
page as interactive HTML and, when static image export is available,
826+
saves a static image of it for the gallery thumbnail.
828827
"""
829828

830829
def render(self, fig_dict):

‎plotly/io/_sg_scraper.py‎

Lines changed: 32 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -43,52 +43,32 @@
4343

4444

4545
def plotly_sg_scraper(block, block_vars, gallery_conf, **kwargs):
46-
"""Scrape Plotly figures for galleries of examples using
47-
sphinx-gallery.
48-
49-
Examples should use ``plotly.io.show()`` (or the equivalent
50-
``fig.show()``) to display the figure with the custom
51-
``sphinx_gallery_png`` renderer, which is made the default renderer as a
52-
side effect of importing this module. Parallel builds on sphinx-gallery
53-
0.21 and earlier also need :func:`reset_renderer`, since their worker
54-
processes never import it.
55-
56-
Every figure shown that way is embedded in the page as interactive HTML,
57-
and written to the gallery image directory as a static image, which
58-
sphinx-gallery uses to generate the thumbnail of the example.
59-
60-
A figure that is instead displayed by making it the last expression of a
61-
code block (sphinx-gallery's repr capture) gets a static image too, so
62-
that it can also serve as the thumbnail; its HTML is embedded by
63-
sphinx-gallery itself.
64-
65-
Static image export requires Kaleido and a Chromium-based browser (the
66-
``plotly_get_chrome`` command installs one); when unavailable, a warning
67-
is emitted once per build and the examples fall back to placeholder
68-
thumbnails, with the interactive figures unaffected.
46+
"""Scrape Plotly figures for sphinx-gallery.
47+
48+
Figures shown with ``fig.show()`` (using the ``sphinx_gallery_png``
49+
renderer, which importing this module selects) are embedded in the page
50+
as interactive HTML. Those figures, and ones displayed as the last
51+
expression of a code block, are also saved as static images for the
52+
gallery thumbnail when Kaleido is available. For parallel builds, see
53+
``reset_renderer``.
6954
7055
Parameters
7156
----------
7257
block : tuple
73-
A tuple containing the (label, content, line_number) of the block.
58+
The (label, content, line_number) of the code block.
7459
block_vars : dict
7560
Dict of block variables.
7661
gallery_conf : dict
77-
Contains the configuration of Sphinx-Gallery
62+
Configuration of Sphinx-Gallery (unused, but part of the scraper
63+
interface).
7864
**kwargs : dict
79-
Additional keyword arguments.
80-
The ``format`` kwarg is used to set the file extension
81-
of the static images (currently only 'png' and 'svg' are supported).
65+
``format`` sets the static image format, ``"png"`` (default) or
66+
``"svg"``.
8267
8368
Returns
8469
-------
8570
rst : str
86-
The ReSTructuredText that will be rendered to HTML containing
87-
the images.
88-
89-
Notes
90-
-----
91-
Add this function to the image scrapers
71+
The reStructuredText embedding the figures.
9272
"""
9373
image_format = kwargs.get("format", "png")
9474
if image_format not in ("png", "svg"):
@@ -124,44 +104,12 @@ def plotly_sg_scraper(block, block_vars, gallery_conf, **kwargs):
124104

125105

126106
def reset_renderer(gallery_conf, fname, *, when=None):
127-
"""Select the ``sphinx_gallery_png`` renderer, as a sphinx-gallery resetter.
128-
129-
Importing this module selects that renderer too, but the worker processes
130-
of a parallel build never import it: ``conf.py`` is read only in the
131-
parent process, and ``image_scrapers=("plotly",)`` reaches a worker as a
132-
plain string that sphinx-gallery resolves only after the example has run.
133-
The example therefore executes with the default ``browser`` renderer,
134-
whose ``fig.show()`` serves the figure from a local web server and waits
135-
for a browser that a worker does not have, hanging the build.
136-
137-
Naming this function in ``reset_modules`` runs it in every worker, before
138-
each example::
139-
140-
sphinx_gallery_conf = {
141-
...
142-
"image_scrapers": ("plotly",),
143-
"reset_modules": ("matplotlib", "plotly.io._sg_scraper.reset_renderer"),
144-
}
145-
146-
Passing it by name rather than importing it keeps ``sphinx_gallery_conf``
147-
picklable, which Sphinx needs in order to cache the environment.
148-
149-
Up to and including sphinx-gallery 0.21, ``image_scrapers`` is resolved
150-
only after an example has run, which is what makes this necessary. From
151-
0.22 it is resolved beforehand and selects the renderer itself, so this
152-
resetter is redundant there -- but harmless, and still worth configuring
153-
if the documentation is also built against older sphinx-gallery.
107+
"""Select the ``sphinx_gallery_png`` renderer before each example.
154108
155-
Parameters
156-
----------
157-
gallery_conf : dict
158-
Contains the configuration of Sphinx-Gallery (unused).
159-
fname : str
160-
Name of the example file about to be executed (unused).
161-
when : str or None
162-
Whether sphinx-gallery is resetting before or after the example
163-
(unused). Sphinx-gallery passes it by keyword, and only to resetters
164-
that accept it.
109+
Parallel builds with sphinx-gallery < 0.22 need this, as their worker
110+
processes never import this module: add
111+
``"plotly.io.sg_scraper.reset_renderer"`` to ``reset_modules`` in
112+
``sphinx_gallery_conf``.
165113
"""
166114
plotly.io.renderers.default = "sphinx_gallery_png"
167115

@@ -222,19 +170,24 @@ def _start_export_server():
222170
_export_server_state = "running"
223171

224172

173+
def _warn(msg, *args):
174+
"""Log a warning, through Sphinx if possible so that builds can suppress
175+
it with ``suppress_warnings = ["plotly.sg_scraper"]``."""
176+
try:
177+
from sphinx.util.logging import getLogger
178+
except Exception:
179+
logging.getLogger(__name__).warning(msg, *args)
180+
else:
181+
getLogger(__name__).warning(msg, *args, type="plotly", subtype="sg_scraper")
182+
183+
225184
def _abandon_export_server(exc):
226185
"""Stop using the shared browser; return whether a retry makes sense."""
227186
global _export_server_state
228187
if _export_server_state != "running":
229188
return False
230189
_export_server_state = "disabled"
231-
try:
232-
from sphinx.util.logging import getLogger
233-
234-
log = getLogger(__name__).info
235-
except Exception:
236-
log = logging.getLogger(__name__).info
237-
log(
190+
_warn(
238191
"The shared plotly static image export browser failed with '%s: %s'; "
239192
"falling back to one browser per exported figure.",
240193
type(exc).__name__,
@@ -260,15 +213,7 @@ def _static_export_available():
260213
try:
261214
_export_image({"data": []}, None, "png")
262215
except Exception as exc:
263-
try:
264-
from sphinx.util.logging import getLogger
265-
266-
warn = functools.partial(
267-
getLogger(__name__).warning, type="plotly", subtype="sg_scraper"
268-
)
269-
except Exception:
270-
warn = logging.getLogger(__name__).warning
271-
warn(
216+
_warn(
272217
"plotly static image export is unavailable, so example "
273218
"thumbnails will fall back to a placeholder image. Static "
274219
"export requires Kaleido and a Chromium-based browser "

‎plotly/io/sg_scraper.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# ruff: noqa: F401
2+
from ._sg_scraper import plotly_sg_scraper, reset_renderer

‎tests/test_io/test_renderers.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,8 @@ def test_repr_html(renderer):
313313
plotlyjs_content = get_plotlyjs()
314314
sri_hash = _generate_sri_hash(plotlyjs_content)
315315

316-
# The fallback sizes like the html renderers: layout height, else 525px
317316
template = (
318-
'<div style="height:525px; width:100%;"> <script>'
317+
'<div style="height:100%; width:100%;"> <script>'
319318
"window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n "
320319
'<script charset="utf-8" src="'
321320
+ plotly_cdn_url()

‎tests/test_io/test_sg_scraper.py‎

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def test_scraper_bad_format(gallery):
207207
gallery.scrape()
208208

209209

210-
def test_scraper_export_server_fallback(gallery, monkeypatch):
210+
def test_scraper_export_server_fallback(gallery, monkeypatch, caplog):
211211
"""A shared browser dying mid-build falls back to per-export browsers."""
212212
import plotly.io._sg_scraper as sg_scraper
213213

@@ -228,6 +228,10 @@ def flaky_write_image(*args, **kwargs):
228228
assert rst.count('class="plotly-graph-div"') == 1
229229
assert_image_color(Path(gallery.paths[0]), COLORS[0])
230230
assert sg_scraper._export_server_state == "disabled"
231+
assert any(
232+
r.levelname == "WARNING" and "falling back" in r.getMessage()
233+
for r in caplog.records
234+
)
231235

232236
# With no server left to abandon, an export failure is fatal
233237
failed.clear()
@@ -271,20 +275,6 @@ def kaleido_warnings():
271275
assert len(kaleido_warnings()) == 1
272276

273277

274-
def test_repr_html_fallback_size(monkeypatch):
275-
"""The repr of a figure must have a usable pixel height, not "100%".
276-
277-
With the (non-mimetype) sphinx_gallery_png renderer selected, sphinx-
278-
gallery captures ``_repr_html_``, whose output ends up in a container
279-
with no set height.
280-
"""
281-
monkeypatch.setattr(pio.renderers, "default", "sphinx_gallery_png")
282-
html = go.Figure()._repr_html_()
283-
assert 'style="height:525px; width:100%;"' in html
284-
fig = go.Figure(layout={"height": 400})
285-
assert 'style="height:400px; width:100%;"' in fig._repr_html_()
286-
287-
288278
def test_image_scrapers_by_name(monkeypatch):
289279
"""`image_scrapers=("plotly",)` must resolve through sphinx-gallery."""
290280
from sphinx_gallery.gen_rst import _get_callables
@@ -310,7 +300,7 @@ def test_reset_renderer(monkeypatch):
310300

311301
monkeypatch.setattr(pio.renderers, "default", "browser")
312302
# By name, so that sphinx_gallery_conf stays picklable
313-
conf = {"reset_modules": ("plotly.io._sg_scraper.reset_renderer",)}
303+
conf = {"reset_modules": ("plotly.io.sg_scraper.reset_renderer",)}
314304
# Let sphinx-gallery resolve and call it, so that the signature it
315305
# dispatches on is covered as well
316306
clean_modules(conf, "plot_example.py", "before")

0 commit comments

Comments
 (0)