diff --git a/CHANGELOG.md b/CHANGELOG.md index fdd156f882f..d7df478ff65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). ### Added +- Added image export support using [Kaleido](https://github.com/plotly/Kaleido). The image export backend can be configured using the new `engine` argument to `plotly.io.to_image` and `plotly.io.write_image`. The `engine` argument may be set to `"kaleido"`, `"orca"`, or `"auto"`. The default is `engine="auto"`, in which case the Kaleido backend is enabled if the `kaleido` package from PyPI is installed, otherwise Orca is used. ([#2613](https://github.com/plotly/plotly.py/pull/2613)). - `px.NO_COLOR` constant to override wide-form color assignment in Plotly Express ([#2614](https://github.com/plotly/plotly.py/pull/2614)) - `facet_row_spacing` and `facet_col_spacing` added to Plotly Express cartesian 2d functions ([#2614](https://github.com/plotly/plotly.py/pull/2614)) @@ -28,7 +29,6 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Updated Plotly.js to version 1.54.5. See the [plotly.js CHANGELOG](https://github.com/plotly/plotly.js/blob/v1.54.5/CHANGELOG.md) for more information. - `add_traces()` now accepts bare `int`-like values for `rows`/`cols` as well as lists thereof ([#2546](https://github.com/plotly/plotly.py/pull/2546)), with thanks to [@MCBoarder289](https://github.com/MCBoarder289) for the contribution! - ### Fixed - `row`/`col` now accept `int`-like values, not strictly `int` values ([#2451](https://github.com/plotly/plotly.py/pull/2451)), with thanks to [@MCBoarder289](https://github.com/MCBoarder289) for the contribution! diff --git a/README.md b/README.md index 015327e9c29..d7ba3b8915b 100644 --- a/README.md +++ b/README.md @@ -133,12 +133,26 @@ jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget@4. Please check out our [Troubleshooting guide](https://plotly.com/python/troubleshooting/) if you run into any problems with JupyterLab. -### Static Image Export +### Static Image Export with Kaleido plotly.py supports static image export using the `to_image` and `write_image` -functions in the `plotly.io` package. This functionality requires the -installation of the plotly [orca](https://github.com/plotly/orca) command line utility and the -[`psutil`](https://github.com/giampaolo/psutil) Python package. +functions in the `plotly.io` module. This functionality requires the +[`kaleido`](https://github.com/plotly/Kaleido) package which can be installed +using pip... + +``` +$ pip install -U kaleido +``` + +or conda. +``` +$ conda install -c plotly python-kaleido +``` + +### Static Image Export with Orca +While Kaleido is now the recommended image export approach because it is easier to install and more widely compatible, image export can also be supported +by the legacy [orca](https://github.com/plotly/orca) command line utility and the + [`psutil`](https://github.com/giampaolo/psutil) Python package. These dependencies can both be installed using conda: diff --git a/doc/python/orca-management.md b/doc/python/orca-management.md index 061cca29cd5..8df2062bdce 100644 --- a/doc/python/orca-management.md +++ b/doc/python/orca-management.md @@ -34,16 +34,72 @@ jupyter: --- ### Overview -This section covers the lower-level details of how plotly.py uses orca to perform static image generation. Please refer to the [Static Image Export](/python/static-image-export/) section for general information on creating static images from plotly.py figures. +This section covers the lower-level details of how plotly.py can use orca to perform static image generation. -### What is Orca? +> Orca is no longer the recommended way to do static image export. We now recommend Kaleido, as described in the [Static Image Export](/python/static-image-export/) section . + +Please refer to the [Static Image Export](/python/static-image-export/) section for general information on creating static images from plotly.py figures. + +### What is orca? Orca is an [Electron](https://electronjs.org/) application that inputs plotly figure specifications and converts them into static images. Orca can run as a command-line utility or as a long-running server process. In order to provide the fastest possible image export experience, plotly.py launches orca in server mode, and communicates with it over a local port. See https://github.com/plotly/orca for more information. By default, plotly.py launches the orca server process the first time an image export operation is performed, and then leaves it running until the main Python process exits. Because of this, the first image export operation in an interactive session will typically take a couple of seconds, but then all subsequent export operations will be significantly faster, since the server is already running. +### Installing orca +There are 3 general approaches to installing orca and its Python dependencies. + +##### conda +Using the [conda](https://conda.io/docs/) package manager, you can install these dependencies in a single command: +``` +$ conda install -c plotly plotly-orca==1.2.1 psutil requests +``` + +**Note:** Even if you do not want to use conda to manage your Python dependencies, it is still useful as a cross platform tool for managing native libraries and command-line utilities (e.g. git, wget, graphviz, boost, gcc, nodejs, cairo, etc.). For this use-case, start with [Miniconda](https://conda.io/miniconda.html) (~60MB) and tell the installer to add itself to your system `PATH`. Then run `conda install plotly-orca==1.2.1` and the orca executable will be available system wide. + +##### npm + pip +You can use the [npm](https://www.npmjs.com/get-npm) package manager to install `orca` (and its `electron` dependency), and then use pip to install `psutil`: + +``` +$ npm install -g electron@1.8.4 orca +$ pip install psutil requests +``` + +##### Standalone Binaries + pip +If you are unable to install conda or npm, you can install orca as a precompiled binary for your operating system. Follow the instructions in the orca [README](https://github.com/plotly/orca) to install orca and add it to your system `PATH`. Then use pip to install `psutil`. + +``` +$ pip install psutil requests +``` + + +### Install orca on Google Colab +``` +!pip install plotly>=4.7.1 +!wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca +!chmod +x /usr/local/bin/orca +!apt-get install xvfb libgtk2.0-0 libgconf-2-4 +``` + +Once this is done you can use this code to make, show and export a figure: + +```python +import plotly.graph_objects as go +fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) ) +fig.write_image("fig1.svg") +fig.write_image("fig1.png") +``` + +The files can then be downloaded with: + +```python +from google.colab import files +files.download('fig1.svg') +files.download('fig1.png') +``` + ### Create a Figure -Now let's create a simple scatter plot with 100 random points of variying color and size. +Now let's create a simple scatter plot with 100 random points of varying color and size. ```python import plotly.graph_objects as go @@ -198,7 +254,7 @@ In addition to the `executable` property, the `plotly.io.orca.config` object can - **`timeout`**: The number of seconds of inactivity required before the orca server is shut down. For example, if timeout is set to 20, then the orca server will shutdown once is has not been used for at least 20 seconds. If timeout is set to `None` (the default), then the server will not be automatically shut down due to inactivity. - **`default_width`**: The default pixel width to use on image export. - **`default_height`**: The default pixel height to use on image export. - - **`default_scale`**: The default image scale facor applied on image export. + - **`default_scale`**: The default image scale factor applied on image export. - **`default_format`**: The default image format used on export. One of `"png"`, `"jpeg"`, `"webp"`, `"svg"`, `"pdf"`, or `"eps"`. - **`mathjax`**: Location of the MathJax bundle needed to render LaTeX characters. Defaults to a CDN location. If fully offline export is required, set this to a local MathJax bundle. - **`topojson`**: Location of the topojson files needed to render choropleth traces. Defaults to a CDN location. If fully offline export is required, set this to a local directory containing the [Plotly.js topojson files](https://github.com/plotly/plotly.js/tree/master/dist/topojson). @@ -207,4 +263,4 @@ In addition to the `executable` property, the `plotly.io.orca.config` object can ### Saving Configuration Settings -Configuration options can optionally be saved to the `~/.plotly/` directory by calling the `plotly.io.config.save()` method. Saved setting will be automatically loaded at the start of future sessions. \ No newline at end of file +Configuration options can optionally be saved to the `~/.plotly/` directory by calling the `plotly.io.config.save()` method. Saved setting will be automatically loaded at the start of future sessions. diff --git a/doc/python/static-image-export.md b/doc/python/static-image-export.md index 6d1b68b8bbe..62d87dd03e3 100644 --- a/doc/python/static-image-export.md +++ b/doc/python/static-image-export.md @@ -37,39 +37,27 @@ jupyter: ### Interactive vs Static Export -Plotly figures are interactive when viewed in a web browser: you can hover over data points, pan and zoom axes, and show and hide traces by clicking or double-clicking on the legend. You can export figures either to static image file formats like PNG, JEPG, SVG or PDF or you can [export them to HTML files which can be opened in a browser and remain interactive](/python/interactive-html-export/). This page explains how to do the former. +Plotly figures are interactive when viewed in a web browser: you can hover over data points, pan and zoom axes, and show and hide traces by clicking or double-clicking on the legend. You can export figures either to static image file formats like PNG, JPEG, SVG or PDF or you can [export them to HTML files which can be opened in a browser and remain interactive](/python/interactive-html-export/). This page explains how to do the former. #### Install Dependencies -Static image generation requires the [orca](https://github.com/plotly/orca) commandline utility and the [psutil](https://github.com/giampaolo/psutil) and [requests](https://2.python-requests.org/en/master/) Python libraries. There are 3 general approach to installing these dependencies. - -##### conda -Using the [conda](https://conda.io/docs/) package manager, you can install these dependencies in a single command: +Static image generation requires either [Kaleido](https://github.com/plotly/Kaleido) (recommended) or [orca](https://github.com/plotly/orca) (legacy). The `kaleido` package can be installed using pip... ``` -$ conda install -c plotly plotly-orca==1.2.1 psutil requests +$ pip install -U kaleido ``` -**Note:** Even if you do not want to use conda to manage your Python dependencies, it is still useful as a cross platform tool for managing native libraries and command-line utilities (e.g. git, wget, graphviz, boost, gcc, nodejs, cairo, etc.). For this use-case, start with [Miniconda](https://conda.io/miniconda.html) (~60MB) and tell the installer to add itself to your system `PATH`. Then run `conda install plotly-orca==1.2.1` and the orca executable will be available system wide. - -##### npm + pip -You can use the [npm](https://www.npmjs.com/get-npm) package manager to install `orca` (and its `electron` dependency), and then use pip to install `psutil`: - -``` -$ npm install -g electron@1.8.4 orca -$ pip install psutil requests +or conda. ``` +$ conda install -c plotly python-kaleido +``` -##### Standalone Binaries + pip -If you are unable to install conda or npm, you can install orca as a precompiled binary for your operating system. Follow the instructions in the orca [README](https://github.com/plotly/orca) to install orca and add it to your system `PATH`. Then use pip to install `psutil`. +While Kaleido is now the recommended approach, image export can also be supported by the legacy [orca](https://github.com/plotly/orca) command line utility. See the [Orca Management](/python/orca-management/) section for instructions on installing, configuring, and troubleshooting orca. -``` -$ pip install psutil requests -``` ### Create a Figure -Now let's create a simple scatter plot with 100 random points of variying color and size. +Now let's create a simple scatter plot with 100 random points of varying color and size. ```python import plotly.graph_objects as go @@ -116,7 +104,7 @@ If you are running this notebook live, click to [open the output directory](./im #### Raster Formats: PNG, JPEG, and WebP -Orca can output figures to several raster image formats including **PNG**, ... +plotly.py can output figures to several raster image formats including **PNG**, ... ```python fig.write_image("images/fig1.png") @@ -137,7 +125,7 @@ fig.write_image("images/fig1.webp") #### Vector Formats: SVG and PDF... -Orca can also output figures in several vector formats including **SVG**, ... +plotly.py can also output figures in several vector formats including **SVG**, ... ```python fig.write_image("images/fig1.svg") @@ -157,33 +145,6 @@ fig.write_image("images/fig1.eps") **Note:** It is important to note that any figures containing WebGL traces (i.e. of type `scattergl`, `heatmapgl`, `contourgl`, `scatter3d`, `surface`, `mesh3d`, `scatterpolargl`, `cone`, `streamtube`, `splom`, or `parcoords`) that are exported in a vector format will include encapsulated rasters, instead of vectors, for some parts of the image. - -### Install orca on Google Colab -``` -!pip install plotly>=4.7.1 -!wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca -!chmod +x /usr/local/bin/orca -!apt-get install xvfb libgtk2.0-0 libgconf-2-4 -``` - -Once this is done you can use this code to make, show and export a figure: - -```python -import plotly.graph_objects as go -fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) ) -fig.write_image("fig1.svg") -fig.write_image("fig1.png") -``` - -The files can then be downloaded with: - -```python -from google.colab import files -files.download('fig1.svg') -files.download('fig1.png') -``` - - ### Get Image as Bytes The `plotly.io.to_image` function is used to return an image as a bytes object. You can also use the `.to_image` graph object figure method. @@ -215,7 +176,45 @@ img_bytes = fig.to_image(format="png", width=600, height=350, scale=2) Image(img_bytes) ``` -### Summary -In summary, to export high-quality static images from plotly.py, all you need to do is install orca, psutil, and requests and then use the `plotly.io.write_image` and `plotly.io.to_image` functions (or the `.write_image` and `.to_image` graph object figure methods). + +### Specify Image Export Engine +If `kaleido` is installed, it will automatically be used to perform image export. If it is not installed, plotly.py will attempt to use orca instead. The `engine` argument to the `to_image` and `write_image` functions can be used to override this default behavior. + +Here is an example of specifying that orca should be used: +```python +fig.to_image(format="png", engine="orca") +``` + +And, here is an example of specifying that Kaleido should be used: +```python +fig.to_image(format="png", engine="kaleido") +``` + + -If you want to know more about how the orca integration works, or if you need to troubleshoot an issue, please check out the [Orca Management](/python/orca-management/) section. \ No newline at end of file + +### Image Export Settings (Kaleido) +Various image export settings can be configured using the `plotly.io.kaleido.scope` object. For example, the `default_format` property can be used to specify that the default export format should be `svg` instead of `png` + +```python +import plotly.io as pio +pio.kaleido.scope.default_format = "svg" +``` + +Here is a complete listing of the available image export settings: + + - **`default_width`**: The default pixel width to use on image export. + - **`default_height`**: The default pixel height to use on image export. + - **`default_scale`**: The default image scale factor applied on image export. + - **`default_format`**: The default image format used on export. One of `"png"`, `"jpeg"`, `"webp"`, `"svg"`, `"pdf"`, or `"eps"`. + - **`mathjax`**: Location of the MathJax bundle needed to render LaTeX characters. Defaults to a CDN location. If fully offline export is required, set this to a local MathJax bundle. + - **`topojson`**: Location of the topojson files needed to render choropleth traces. Defaults to a CDN location. If fully offline export is required, set this to a local directory containing the [Plotly.js topojson files](https://github.com/plotly/plotly.js/tree/master/dist/topojson). + - **`mapbox_access_token`**: The default Mapbox access token. + + + +### Image Export Settings (Orca) +See the [Orca Management](/python/orca-management/) section for information on how to specify image export settings when using orca. + +### Summary +In summary, to export high-quality static images from plotly.py, all you need to do is install the `kaleido` package and then use the `plotly.io.write_image` and `plotly.io.to_image` functions (or the `.write_image` and `.to_image` graph object figure methods). diff --git a/packages/python/plotly/plotly/basedatatypes.py b/packages/python/plotly/plotly/basedatatypes.py index f91e4a96aee..f10f1daffa8 100644 --- a/packages/python/plotly/plotly/basedatatypes.py +++ b/packages/python/plotly/plotly/basedatatypes.py @@ -3172,6 +3172,12 @@ def to_image(self, *args, **kwargs): True if the figure should be validated before being converted to an image, False otherwise. + engine: str + Image export engine to use: + - "kaleido": Use Kaleido for image export + - "orca": Use Orca for image export + - "auto" (default): Use Kaleido if installed, otherwise use orca + Returns ------- bytes @@ -3231,6 +3237,11 @@ def write_image(self, *args, **kwargs): True if the figure should be validated before being converted to an image, False otherwise. + engine: str + Image export engine to use: + - "kaleido": Use Kaleido for image export + - "orca": Use Orca for image export + - "auto" (default): Use Kaleido if installed, otherwise use orca Returns ------- None diff --git a/packages/python/plotly/plotly/io/__init__.py b/packages/python/plotly/plotly/io/__init__.py index ab9f9218c70..cdbf473d1fd 100644 --- a/packages/python/plotly/plotly/io/__init__.py +++ b/packages/python/plotly/plotly/io/__init__.py @@ -2,8 +2,8 @@ import sys if sys.version_info < (3, 7): - from ._orca import to_image, write_image - from . import orca + from ._kaleido import to_image, write_image + from . import orca, kaleido from ._json import to_json, from_json, read_json, write_json from ._templates import templates, to_templated from ._html import to_html, write_html @@ -29,10 +29,10 @@ else: __all__, __getattr__, __dir__ = relative_import( __name__, - [".orca", ".base_renderers"], + [".orca", ".kaleido", ".base_renderers"], [ - "._orca.to_image", - "._orca.write_image", + "._kaleido.to_image", + "._kaleido.write_image", "._json.to_json", "._json.from_json", "._json.read_json", diff --git a/packages/python/plotly/plotly/io/_base_renderers.py b/packages/python/plotly/plotly/io/_base_renderers.py index 9cd7fbfb72b..10226ad71e0 100644 --- a/packages/python/plotly/plotly/io/_base_renderers.py +++ b/packages/python/plotly/plotly/io/_base_renderers.py @@ -112,6 +112,7 @@ def __init__( width=None, height=None, scale=None, + engine="auto", ): self.mime_type = mime_type @@ -120,10 +121,7 @@ def __init__( self.width = width self.height = height self.scale = scale - - def activate(self): - # Start up orca server to reduce the delay on first render - ensure_server() + self.engine = engine def to_mimebundle(self, fig_dict): image_bytes = to_image( @@ -133,6 +131,7 @@ def to_mimebundle(self, fig_dict): height=self.height, scale=self.scale, validate=False, + engine=self.engine, ) if self.b64_encode: @@ -146,14 +145,14 @@ def to_mimebundle(self, fig_dict): class PngRenderer(ImageRenderer): """ Renderer to display figures as static PNG images. This renderer requires - the orca command-line utility and is broadly compatible across IPython - environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode, - PyCharm, etc) and nbconvert targets (HTML, PDF, etc.). + either the kaleido package or the orca command-line utility and is broadly + compatible across IPython environments (classic Jupyter Notebook, JupyterLab, + QtConsole, VSCode, PyCharm, etc) and nbconvert targets (HTML, PDF, etc.). mime type: 'image/png' """ - def __init__(self, width=None, height=None, scale=None): + def __init__(self, width=None, height=None, scale=None, engine="auto"): super(PngRenderer, self).__init__( mime_type="image/png", b64_encode=True, @@ -161,20 +160,21 @@ def __init__(self, width=None, height=None, scale=None): width=width, height=height, scale=scale, + engine=engine, ) class SvgRenderer(ImageRenderer): """ Renderer to display figures as static SVG images. This renderer requires - the orca command-line utility and is broadly compatible across IPython - environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode, - PyCharm, etc) and nbconvert targets (HTML, PDF, etc.). + either the kaleido package or the orca command-line utility and is broadly + compatible across IPython environments (classic Jupyter Notebook, JupyterLab, + QtConsole, VSCode, PyCharm, etc) and nbconvert targets (HTML, PDF, etc.). mime type: 'image/svg+xml' """ - def __init__(self, width=None, height=None, scale=None): + def __init__(self, width=None, height=None, scale=None, engine="auto"): super(SvgRenderer, self).__init__( mime_type="image/svg+xml", b64_encode=False, @@ -182,20 +182,21 @@ def __init__(self, width=None, height=None, scale=None): width=width, height=height, scale=scale, + engine=engine, ) class JpegRenderer(ImageRenderer): """ Renderer to display figures as static JPEG images. This renderer requires - the orca command-line utility and is broadly compatible across IPython - environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode, - PyCharm, etc) and nbconvert targets (HTML, PDF, etc.). + either the kaleido package or the orca command-line utility and is broadly + compatible across IPython environments (classic Jupyter Notebook, JupyterLab, + QtConsole, VSCode, PyCharm, etc) and nbconvert targets (HTML, PDF, etc.). mime type: 'image/jpeg' """ - def __init__(self, width=None, height=None, scale=None): + def __init__(self, width=None, height=None, scale=None, engine="auto"): super(JpegRenderer, self).__init__( mime_type="image/jpeg", b64_encode=True, @@ -203,19 +204,20 @@ def __init__(self, width=None, height=None, scale=None): width=width, height=height, scale=scale, + engine=engine, ) class PdfRenderer(ImageRenderer): """ Renderer to display figures as static PDF images. This renderer requires - the orca command-line utility and is compatible with JupyterLab and the - LaTeX-based nbconvert export to PDF. + either the kaleido package or the orca command-line utility and is compatible + with JupyterLab and the LaTeX-based nbconvert export to PDF. mime type: 'application/pdf' """ - def __init__(self, width=None, height=None, scale=None): + def __init__(self, width=None, height=None, scale=None, engine="auto"): super(PdfRenderer, self).__init__( mime_type="application/pdf", b64_encode=True, @@ -223,6 +225,7 @@ def __init__(self, width=None, height=None, scale=None): width=width, height=height, scale=scale, + engine=engine, ) diff --git a/packages/python/plotly/plotly/io/_kaleido.py b/packages/python/plotly/plotly/io/_kaleido.py new file mode 100644 index 00000000000..eea208dcf89 --- /dev/null +++ b/packages/python/plotly/plotly/io/_kaleido.py @@ -0,0 +1,263 @@ +from __future__ import absolute_import +from six import string_types +import os +import plotly +from plotly.io._utils import validate_coerce_fig_to_dict + +try: + from kaleido.scopes.plotly import PlotlyScope + + scope = PlotlyScope() + + # Compute absolute path to the 'plotly/package_data/' directory + root_dir = os.path.dirname(os.path.abspath(plotly.__file__)) + package_dir = os.path.join(root_dir, "package_data") + scope.plotlyjs = os.path.join(package_dir, "plotly.min.js") + scope.mathjax = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js" +except ImportError: + PlotlyScope = None + scope = None + + +def to_image( + fig, format=None, width=None, height=None, scale=None, validate=True, engine="auto" +): + """ + Convert a figure to a static image bytes string + + Parameters + ---------- + fig: + Figure object or dict representing a figure + + format: str or None + The desired image format. One of + - 'png' + - 'jpg' or 'jpeg' + - 'webp' + - 'svg' + - 'pdf' + - 'eps' (Requires the poppler library to be installed and on the PATH) + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_format` if engine is "kaleido" + - `plotly.io.orca.config.default_format` if engine is "orca" + + width: int or None + The width of the exported image in layout pixels. If the `scale` + property is 1.0, this will also be the width of the exported image + in physical pixels. + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_width` if engine is "kaleido" + - `plotly.io.orca.config.default_width` if engine is "orca" + + height: int or None + The height of the exported image in layout pixels. If the `scale` + property is 1.0, this will also be the height of the exported image + in physical pixels. + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_height` if engine is "kaleido" + - `plotly.io.orca.config.default_height` if engine is "orca" + + scale: int or float or None + The scale factor to use when exporting the figure. A scale factor + larger than 1.0 will increase the image resolution with respect + to the figure's layout pixel dimensions. Whereas as scale factor of + less than 1.0 will decrease the image resolution. + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_scale` if engine is "kaleido" + - `plotly.io.orca.config.default_scale` if engine is "orca" + + + validate: bool + True if the figure should be validated before being converted to + an image, False otherwise. + + engine: str + Image export engine to use: + - "kaleido": Use Kaleido for image export + - "orca": Use Orca for image export + - "auto" (default): Use Kaleido if installed, otherwise use orca + + Returns + ------- + bytes + The image data + """ + # Handle engine + # ------------- + if engine == "auto": + if scope is not None: + engine = "kaleido" + else: + engine = "orca" + + if engine == "orca": + # Fall back to legacy orca image export path + from ._orca import to_image as to_image_orca + + return to_image_orca( + fig, + format=format, + width=width, + height=height, + scale=scale, + validate=validate, + ) + elif engine != "kaleido": + raise ValueError( + "Invalid image export engine specified: {engine}".format( + engine=repr(engine) + ) + ) + + # Raise informative error message if Kaleido is not installed + if scope is None: + raise ValueError( + """ +Image export using the "kaleido" engine requires the kaleido package, +which can be installed using pip: + $ pip install -U kaleido +""" + ) + + # Validate figure + # --------------- + fig_dict = validate_coerce_fig_to_dict(fig, validate) + img_bytes = scope.transform( + fig_dict, format=format, width=width, height=height, scale=scale + ) + + return img_bytes + + +def write_image( + fig, + file, + format=None, + scale=None, + width=None, + height=None, + validate=True, + engine="auto", +): + """ + Convert a figure to a static image and write it to a file or writeable + object + + Parameters + ---------- + fig: + Figure object or dict representing a figure + + file: str or writeable + A string representing a local file path or a writeable object + (e.g. an open file descriptor) + + format: str or None + The desired image format. One of + - 'png' + - 'jpg' or 'jpeg' + - 'webp' + - 'svg' + - 'pdf' + - 'eps' (Requires the poppler library to be installed and on the PATH) + + If not specified and `file` is a string then this will default to the + file extension. If not specified and `file` is not a string then this + will default to: + - `plotly.io.kaleido.scope.default_format` if engine is "kaleido" + - `plotly.io.orca.config.default_format` if engine is "orca" + + width: int or None + The width of the exported image in layout pixels. If the `scale` + property is 1.0, this will also be the width of the exported image + in physical pixels. + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_width` if engine is "kaleido" + - `plotly.io.orca.config.default_width` if engine is "orca" + + height: int or None + The height of the exported image in layout pixels. If the `scale` + property is 1.0, this will also be the height of the exported image + in physical pixels. + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_height` if engine is "kaleido" + - `plotly.io.orca.config.default_height` if engine is "orca" + + scale: int or float or None + The scale factor to use when exporting the figure. A scale factor + larger than 1.0 will increase the image resolution with respect + to the figure's layout pixel dimensions. Whereas as scale factor of + less than 1.0 will decrease the image resolution. + + If not specified, will default to: + - `plotly.io.kaleido.scope.default_scale` if engine is "kaleido" + - `plotly.io.orca.config.default_scale` if engine is "orca" + + validate: bool + True if the figure should be validated before being converted to + an image, False otherwise. + + engine: str + Image export engine to use: + - "kaleido": Use Kaleido for image export + - "orca": Use Orca for image export + - "auto" (default): Use Kaleido if installed, otherwise use orca + + Returns + ------- + None + """ + # Check if file is a string + # ------------------------- + file_is_str = isinstance(file, string_types) + + # Infer format if not specified + # ----------------------------- + if file_is_str and format is None: + _, ext = os.path.splitext(file) + if ext: + format = ext.lstrip(".") + else: + raise ValueError( + """ +Cannot infer image type from output path '{file}'. +Please add a file extension or specify the type using the format parameter. +For example: + + >>> import plotly.io as pio + >>> pio.write_image(fig, file_path, format='png') +""".format( + file=file + ) + ) + + # Request image + # ------------- + # Do this first so we don't create a file if image conversion fails + img_data = to_image( + fig, + format=format, + scale=scale, + width=width, + height=height, + validate=validate, + engine=engine, + ) + + # Open file + # --------- + if file_is_str: + with open(file, "wb") as f: + f.write(img_data) + else: + file.write(img_data) + + +__all__ = ["to_image", "write_image", "scope"] diff --git a/packages/python/plotly/plotly/io/kaleido.py b/packages/python/plotly/plotly/io/kaleido.py new file mode 100644 index 00000000000..c14b315047b --- /dev/null +++ b/packages/python/plotly/plotly/io/kaleido.py @@ -0,0 +1 @@ +from ._kaleido import to_image, write_image, scope diff --git a/packages/python/plotly/plotly/tests/test_optional/test_kaleido/__init__.py b/packages/python/plotly/plotly/tests/test_optional/test_kaleido/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/python/plotly/plotly/tests/test_optional/test_kaleido/test_kaleido.py b/packages/python/plotly/plotly/tests/test_optional/test_kaleido/test_kaleido.py new file mode 100644 index 00000000000..53044f0575f --- /dev/null +++ b/packages/python/plotly/plotly/tests/test_optional/test_kaleido/test_kaleido.py @@ -0,0 +1,101 @@ +import plotly.io as pio +import plotly.io.kaleido +import sys +from contextlib import contextmanager + +if sys.version_info >= (3, 3): + from unittest.mock import Mock +else: + from mock import Mock + +fig = {"layout": {"title": {"text": "figure title"}}} + + +@contextmanager +def mocked_scope(): + # Code to acquire resource, e.g.: + scope_mock = Mock() + original_scope = pio._kaleido.scope + pio._kaleido.scope = scope_mock + try: + yield scope_mock + finally: + pio._kaleido.scope = original_scope + + +def test_kaleido_engine_to_image_returns_bytes(): + result = pio.to_image(fig, format="svg", engine="kaleido", validate=False) + assert result.startswith(b"