| 1 |
"""Trame utilities for running in Jupyter.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import logging |
| 7 |
import os |
| 8 |
from typing import TYPE_CHECKING |
| 9 |
from typing import Concatenate |
| 10 |
from typing import Literal |
| 11 |
|
| 12 |
from trame.widgets import html as html_widgets |
| 13 |
from trame.widgets import vtk as vtk_widgets |
| 14 |
from trame.widgets import vuetify as vuetify2_widgets |
| 15 |
from trame.widgets import vuetify3 as vuetify3_widgets |
| 16 |
|
| 17 |
from pyvista._warn_external import warn_external |
| 18 |
|
| 19 |
try: |
| 20 |
from ipywidgets.widgets import HTML |
| 21 |
except ImportError: |
| 22 |
HTML = object |
| 23 |
|
| 24 |
|
| 25 |
import pyvista as pv |
| 26 |
from pyvista.trame.ui import UI_TITLE |
| 27 |
from pyvista.trame.ui import get_viewer |
| 28 |
from pyvista.trame.views import CLOSED_PLOTTER_ERROR |
| 29 |
from pyvista.trame.views import get_server |
| 30 |
|
| 31 |
if TYPE_CHECKING: |
| 32 |
from collections.abc import Callable |
| 33 |
|
| 34 |
from IPython.display import IFrame |
| 35 |
|
| 36 |
from pyvista.jupyter import JupyterBackendOptions |
| 37 |
from pyvista.plotting.plotter import Plotter |
| 38 |
from pyvista.trame.ui.vuetify2 import Viewer |
| 39 |
|
| 40 |
SERVER_DOWN_MESSAGE = """Trame server has not launched. |
| 41 |
|
| 42 |
You must start the trame server before attempting to `show()` |
| 43 |
with PyVista. |
| 44 |
|
| 45 |
You can use the following snippet to launch the server: |
| 46 |
|
| 47 |
from pyvista.trame.jupyter import launch_server |
| 48 |
await launch_server('{name}').ready |
| 49 |
|
| 50 |
""" |
| 51 |
JUPYTER_SERVER_DOWN_MESSAGE = """Trame server has not launched. |
| 52 |
|
| 53 |
Prior to plotting, please make sure to run `set_jupyter_backend('trame')` when using the |
| 54 |
`'trame'`, `'server'`, or `'client'` Jupyter backends. |
| 55 |
|
| 56 |
import pyvista as pv |
| 57 |
pyvista.set_jupyter_backend('trame') |
| 58 |
|
| 59 |
If this issue persists, please open an issue in PyVista: https://github.com/pyvista/pyvista/issues |
| 60 |
|
| 61 |
""" |
| 62 |
|
| 63 |
logger = logging.getLogger(__name__) |
| 64 |
|
| 65 |
|
| 66 |
class TrameServerDownError(RuntimeError): # numpydoc ignore=PR01 |
| 67 |
"""Exception when trame server is down for Jupyter.""" |
| 68 |
|
| 69 |
def __init__(self, server_name): |
| 70 |
"""Call the base class constructor with the custom message.""" |
| 71 |
super().__init__(SERVER_DOWN_MESSAGE.format(name=server_name)) |
| 72 |
|
| 73 |
|
| 74 |
class TrameJupyterServerDownError(RuntimeError): |
| 75 |
"""Exception when trame server is down for Jupyter.""" |
| 76 |
|
| 77 |
def __init__(self): |
| 78 |
"""Call the base class constructor with the custom message.""" |
| 79 |
# Be incredibly verbose on how users should launch trame server |
| 80 |
# Both warn so it appears at top |
| 81 |
warn_external(JUPYTER_SERVER_DOWN_MESSAGE) # pragma: no cover |
| 82 |
# and Error |
| 83 |
super().__init__(JUPYTER_SERVER_DOWN_MESSAGE) |
| 84 |
|
| 85 |
|
| 86 |
class Widget(HTML): # type: ignore[misc] # numpydoc ignore=PR01 |
| 87 |
"""Custom HTML iframe widget for trame viewer.""" |
| 88 |
|
| 89 |
def __init__(self, viewer, src, width=None, height=None, iframe_attrs=None, **kwargs): |
| 90 |
"""Initialize.""" |
| 91 |
if HTML is object: |
| 92 |
msg = 'Please install `ipywidgets`.' |
| 93 |
raise ImportError(msg) |
| 94 |
# eventually we could maybe expose this, but for now make sure we're at least |
| 95 |
# consistent with matplotlib's color (light gray) |
| 96 |
|
| 97 |
if iframe_attrs is None: |
| 98 |
iframe_attrs = {} |
| 99 |
|
| 100 |
border = 'border: 1px solid rgb(221,221,221);' |
| 101 |
|
| 102 |
iframe_attrs = { |
| 103 |
**iframe_attrs, |
| 104 |
'src': src, |
| 105 |
'class': 'pyvista', |
| 106 |
'style': f'width: {width}; height: {height}; {border}', |
| 107 |
'scrolling': 'no', |
| 108 |
} |
| 109 |
|
| 110 |
iframe_attrs_str = ' '.join(f'{key}="{value!s}"' for key, value in iframe_attrs.items()) |
| 111 |
|
| 112 |
value = f'<iframe {iframe_attrs_str}></iframe>' |
| 113 |
|
| 114 |
super().__init__(value, **kwargs) |
| 115 |
self._viewer = viewer |
| 116 |
self._src = src |
| 117 |
|
| 118 |
@property |
| 119 |
def viewer(self): # numpydoc ignore=RT01 |
| 120 |
"""Get the associated viewer instance.""" |
| 121 |
return self._viewer |
| 122 |
|
| 123 |
@property |
| 124 |
def src(self): # numpydoc ignore=RT01 |
| 125 |
"""Get the src URL.""" |
| 126 |
return self._src |
| 127 |
|
| 128 |
|
| 129 |
class EmbeddableWidget(HTML): # type: ignore[misc] # numpydoc ignore=PR01 |
| 130 |
"""Custom HTML iframe widget for embedding the trame viewer.""" |
| 131 |
|
| 132 |
def __init__(self, plotter, width, height, **kwargs): |
| 133 |
"""Initialize.""" |
| 134 |
if HTML is object: |
| 135 |
msg = 'Please install `ipywidgets`.' |
| 136 |
raise ImportError(msg) |
| 137 |
scene = plotter.export_html(filename=None) |
| 138 |
src = scene.getvalue().replace('"', '"') |
| 139 |
# eventually we could maybe expose this, but for now make sure we're at least |
| 140 |
# consistent with matplotlib's color (light gray) |
| 141 |
border = 'border: 1px solid rgb(221,221,221);' |
| 142 |
value = ( |
| 143 |
f'<iframe srcdoc="{src}" class="pyvista" style="width: {width}; ' |
| 144 |
f'height: {height}; {border}"></iframe>' |
| 145 |
) |
| 146 |
super().__init__(value, **kwargs) |
| 147 |
self._src = src |
| 148 |
|
| 149 |
|
| 150 |
def launch_server(server=None, port=None, host=None, wslink_backend=None, **kwargs): |
| 151 |
"""Launch a trame server for use with Jupyter. |
| 152 |
|
| 153 |
Parameters |
| 154 |
---------- |
| 155 |
server : str, optional |
| 156 |
By default this uses :attr:`pyvista.global_theme.trame.jupyter_server_name |
| 157 |
<pyvista.plotting.themes._TrameConfig.jupyter_server_name>`, which by default is |
| 158 |
set to ``'pyvista-jupyter'``. |
| 159 |
|
| 160 |
If a server name is given and such server is not available yet, it will |
| 161 |
be created otherwise the previously created instance will be returned. |
| 162 |
|
| 163 |
port : int, optional |
| 164 |
The port on which to bind the server. Defaults to 0 to automatically |
| 165 |
find an available port. |
| 166 |
|
| 167 |
host : str, optional |
| 168 |
The host name to bind the server to on launch. Server will bind to |
| 169 |
``127.0.0.1`` by default unless user sets the environment variable ``TRAME_DEFAULT_HOST``. |
| 170 |
|
| 171 |
wslink_backend : str, optional |
| 172 |
The wslink backend that the server should use |
| 173 |
``aiohttp`` by default, ``jupyter`` if the |
| 174 |
`trame_jupyter_extension <https://github.com/Kitware/trame-jupyter-extension>`_ |
| 175 |
is used. |
| 176 |
|
| 177 |
**kwargs : dict, optional |
| 178 |
Any additional keyword arguments to pass to ``pyvista.trame.views.get_server``. |
| 179 |
|
| 180 |
Returns |
| 181 |
------- |
| 182 |
trame_server.core.Server |
| 183 |
The launched Trame server. To ``await`` the launch, use the |
| 184 |
``.ready`` future attribute on the server. |
| 185 |
|
| 186 |
""" |
| 187 |
if server is None: |
| 188 |
server = pv.global_theme.trame.jupyter_server_name |
| 189 |
if isinstance(server, str): |
| 190 |
server = get_server(server, **kwargs) |
| 191 |
if port is None: |
| 192 |
port = pv.global_theme.trame.jupyter_server_port |
| 193 |
if host is None: |
| 194 |
# Default to `127.0.0.1` unless user sets TRAME_DEFAULT_HOST |
| 195 |
host = os.environ.get('TRAME_DEFAULT_HOST', '127.0.0.1') |
| 196 |
if ( |
| 197 |
wslink_backend is None and pv.global_theme.trame.jupyter_extension_enabled |
| 198 |
): # pragma: no cover |
| 199 |
wslink_backend = 'jupyter' |
| 200 |
|
| 201 |
# Must enable all used modules |
| 202 |
html_widgets.initialize(server) |
| 203 |
vtk_widgets.initialize(server) |
| 204 |
|
| 205 |
if server.client_type == 'vue2': |
| 206 |
vuetify2_widgets.initialize(server) |
| 207 |
else: |
| 208 |
vuetify3_widgets.initialize(server) |
| 209 |
|
| 210 |
def on_ready(**_): |
| 211 |
logger.debug(f'Server ready: {server}') |
| 212 |
|
| 213 |
if server._running_stage == 0: |
| 214 |
server.controller.on_server_ready.add(on_ready) |
| 215 |
server.start( |
| 216 |
exec_mode='task', |
| 217 |
host=host, |
| 218 |
port=port, |
| 219 |
open_browser=False, |
| 220 |
show_connection_info=False, |
| 221 |
disable_logging=True, |
| 222 |
timeout=0, |
| 223 |
backend=wslink_backend, |
| 224 |
) |
| 225 |
# else, server is already running or launching |
| 226 |
return server |
| 227 |
|
| 228 |
|
| 229 |
def build_url( |
| 230 |
_server, |
| 231 |
ui=None, |
| 232 |
server_proxy_enabled=None, |
| 233 |
server_proxy_prefix=None, |
| 234 |
host='localhost', |
| 235 |
protocol='http', |
| 236 |
): # numpydoc ignore=PR01,RT01 |
| 237 |
"""Build the URL for the iframe.""" |
| 238 |
params = f'?ui={ui}&reconnect=auto' if ui else '?reconnect=auto' |
| 239 |
if server_proxy_enabled is None: |
| 240 |
server_proxy_enabled = pv.global_theme.trame.server_proxy_enabled |
| 241 |
if server_proxy_enabled: |
| 242 |
if server_proxy_prefix is None: |
| 243 |
server_proxy_prefix = pv.global_theme.trame.server_proxy_prefix |
| 244 |
# server_proxy_prefix assumes trailing slash |
| 245 |
prefix = server_proxy_prefix or '' # pragma: no cover |
| 246 |
src = f'{prefix}{_server.port}/index.html{params}' |
| 247 |
else: |
| 248 |
src = f'{protocol}://{host}:{_server.port}/index.html{params}' |
| 249 |
logger.debug(src) |
| 250 |
return src |
| 251 |
|
| 252 |
|
| 253 |
def initialize( |
| 254 |
server, |
| 255 |
plotter, |
| 256 |
mode=None, |
| 257 |
default_server_rendering=True, |
| 258 |
collapse_menu=False, |
| 259 |
**kwargs, |
| 260 |
): # numpydoc ignore=PR01,RT01 |
| 261 |
"""Generate the UI for a given plotter.""" |
| 262 |
state = server.state |
| 263 |
state.trame__title = UI_TITLE |
| 264 |
|
| 265 |
viewer = get_viewer( |
| 266 |
plotter, |
| 267 |
server=server, |
| 268 |
suppress_rendering=mode == 'client', |
| 269 |
) |
| 270 |
|
| 271 |
with viewer.make_layout(server, template_name=plotter._id_name) as layout: |
| 272 |
viewer.layout = layout |
| 273 |
viewer.ui( |
| 274 |
mode=mode, |
| 275 |
default_server_rendering=default_server_rendering, |
| 276 |
collapse_menu=collapse_menu, |
| 277 |
**kwargs, |
| 278 |
) |
| 279 |
|
| 280 |
return viewer |
| 281 |
|
| 282 |
|
| 283 |
def show_trame( |
| 284 |
plotter: Plotter, |
| 285 |
mode: JupyterBackendOptions | str | None = None, |
| 286 |
name: str | None = None, |
| 287 |
server_proxy_enabled: bool | None = None, |
| 288 |
server_proxy_prefix: str | None = None, |
| 289 |
jupyter_extension_enabled: bool | None = None, |
| 290 |
collapse_menu: bool = False, |
| 291 |
add_menu: bool = True, |
| 292 |
add_menu_items: Callable[[Literal['trame', 'server', 'client'], bool, bool], None] |
| 293 |
| None = None, |
| 294 |
default_server_rendering: bool = True, |
| 295 |
handler: Callable[Concatenate[Viewer, str, ...], IFrame] | None = None, |
| 296 |
**kwargs, |
| 297 |
) -> EmbeddableWidget | IFrame | Widget: |
| 298 |
"""Run and display the trame application in jupyter's event loop. |
| 299 |
|
| 300 |
Parameters |
| 301 |
---------- |
| 302 |
plotter : pyvista.Plotter |
| 303 |
The PyVista plotter to show. |
| 304 |
|
| 305 |
mode : str, optional |
| 306 |
The UI view mode. This can be set on the global theme. Options are: |
| 307 |
|
| 308 |
* ``'trame'``: Uses a view that can switch between client and server |
| 309 |
rendering modes. |
| 310 |
* ``'server'``: Uses a view that is purely server rendering. |
| 311 |
* ``'client'``: Uses a view that is purely client rendering (generally |
| 312 |
safe without a virtual frame buffer) |
| 313 |
* ``'html'``: Exports the scene for client rendering that can be |
| 314 |
embedded in a webpage. |
| 315 |
|
| 316 |
name : str, optional |
| 317 |
The name of the trame server on which the UI is defined. |
| 318 |
|
| 319 |
server_proxy_enabled : bool, default: False |
| 320 |
Build a relative URL for use with ``jupyter-server-proxy``. |
| 321 |
|
| 322 |
server_proxy_prefix : str, optional |
| 323 |
URL prefix when using ``server_proxy_enabled``. This can be set |
| 324 |
globally in the theme. To ignore, pass ``False``. For use with |
| 325 |
``jupyter-server-proxy``, often set to ``proxy/``. |
| 326 |
|
| 327 |
jupyter_extension_enabled : bool, default: False |
| 328 |
Build a relative URL for use with ``trame-jupyter-extension``. |
| 329 |
|
| 330 |
collapse_menu : bool, default: False |
| 331 |
Collapse the UI menu (camera controls, etc.) on start. |
| 332 |
|
| 333 |
add_menu : bool, default: True |
| 334 |
Add a UI controls VCard to the VContainer. |
| 335 |
|
| 336 |
add_menu_items : callable, default: None |
| 337 |
Append more UI controls to the VCard menu. Should be a function similar to |
| 338 |
Viewer.ui_controls(). |
| 339 |
|
| 340 |
default_server_rendering : bool, default: True |
| 341 |
Whether to use server-side or client-side rendering on-start when |
| 342 |
using the ``'trame'`` mode. |
| 343 |
|
| 344 |
handler : callable, optional |
| 345 |
Pass a callable that accptes the viewer instance, the string URL, |
| 346 |
and ``**kwargs`` to create custom HTML representations of the output. |
| 347 |
|
| 348 |
.. code-block:: python |
| 349 |
|
| 350 |
import pyvista as pv |
| 351 |
from IPython.display import IFrame |
| 352 |
|
| 353 |
mesh = pyvista.Wavelet() |
| 354 |
|
| 355 |
|
| 356 |
def handler(viewer, src, **kwargs): |
| 357 |
return IFrame(src, '75%', '500px') |
| 358 |
|
| 359 |
|
| 360 |
pl = pv.Plotter(notebook=True) |
| 361 |
_ = pl.add_mesh(mesh) |
| 362 |
iframe = pl.show( |
| 363 |
jupyter_backend='trame', |
| 364 |
jupyter_kwargs=dict(handler=handler), |
| 365 |
return_viewer=True, |
| 366 |
) |
| 367 |
iframe |
| 368 |
|
| 369 |
**kwargs : dict, optional |
| 370 |
Mostly ignored, though ``protocol`` and ``host`` can be use to |
| 371 |
override the iframe src url and ``height`` and ``width`` can be |
| 372 |
used to override the iframe style. Remaining kwargs are passed to |
| 373 |
``ipywidgets.widgets.HTML``. |
| 374 |
|
| 375 |
Returns |
| 376 |
------- |
| 377 |
output : ipywidgets.widgets.HTML or handler result |
| 378 |
Returns a HTML IFrame widget or the result of the passed handler. |
| 379 |
|
| 380 |
""" |
| 381 |
if plotter.render_window is None: |
| 382 |
raise RuntimeError(CLOSED_PLOTTER_ERROR) |
| 383 |
|
| 384 |
if plotter._window_size_unset: |
| 385 |
dw, dh = '100%', '600px' |
| 386 |
else: |
| 387 |
width, height = plotter.window_size |
| 388 |
dw = f'{width}px' |
| 389 |
dh = f'{height}px' |
| 390 |
kwargs.setdefault('width', dw) |
| 391 |
kwargs.setdefault('height', dh) |
| 392 |
|
| 393 |
if mode == 'html': |
| 394 |
return EmbeddableWidget(plotter, **kwargs) |
| 395 |
|
| 396 |
if jupyter_extension_enabled is None: |
| 397 |
jupyter_extension_enabled = pv.global_theme.trame.jupyter_extension_enabled |
| 398 |
|
| 399 |
if name is None: |
| 400 |
server = get_server(name=pv.global_theme.trame.jupyter_server_name) |
| 401 |
else: |
| 402 |
server = get_server(name=name) |
| 403 |
if name is None and not server.running: |
| 404 |
wslink_backend = 'aiohttp' |
| 405 |
if jupyter_extension_enabled: # pragma: no cover |
| 406 |
wslink_backend = 'jupyter' |
| 407 |
|
| 408 |
elegantly_launch(server, wslink_backend=wslink_backend) |
| 409 |
if not server.running: # pragma: no cover |
| 410 |
raise TrameJupyterServerDownError |
| 411 |
elif not server.running: |
| 412 |
raise TrameServerDownError(name) |
| 413 |
|
| 414 |
# Initialize app |
| 415 |
viewer = initialize( |
| 416 |
server, |
| 417 |
plotter, |
| 418 |
mode=mode, |
| 419 |
default_server_rendering=default_server_rendering, |
| 420 |
collapse_menu=collapse_menu, |
| 421 |
add_menu=add_menu, |
| 422 |
add_menu_items=add_menu_items, |
| 423 |
) |
| 424 |
|
| 425 |
if jupyter_extension_enabled: # pragma: no cover |
| 426 |
from trame_client.ui.core import iframe_url_builder_jupyter_extension # noqa: PLC0415 |
| 427 |
|
| 428 |
iframe_attrs = iframe_url_builder_jupyter_extension(viewer.layout) |
| 429 |
src = iframe_attrs['src'] |
| 430 |
else: |
| 431 |
# TODO: The build_url function could possibly be replaced by |
| 432 |
# trame's upstream url builders in trame_client.ui.core |
| 433 |
iframe_attrs = {} |
| 434 |
src = build_url( |
| 435 |
server, |
| 436 |
ui=plotter._id_name, |
| 437 |
server_proxy_enabled=server_proxy_enabled, |
| 438 |
server_proxy_prefix=server_proxy_prefix, |
| 439 |
host=kwargs.get('host', 'localhost'), |
| 440 |
protocol=kwargs.get('protocol', 'http'), |
| 441 |
) |
| 442 |
|
| 443 |
if callable(handler): |
| 444 |
return handler(viewer, src, iframe_attrs=iframe_attrs, **kwargs) |
| 445 |
return Widget(viewer, src, iframe_attrs=iframe_attrs, **kwargs) |
| 446 |
|
| 447 |
|
| 448 |
def elegantly_launch(*args, **kwargs): # numpydoc ignore=PR01 |
| 449 |
"""Elegantly launch the Trame server without await. |
| 450 |
|
| 451 |
This provides a mechanism to launch the Trame Jupyter backend in |
| 452 |
a way that does not require users to await the call. |
| 453 |
|
| 454 |
This is a thin wrapper of |
| 455 |
:func:`launch_server() <pyvista.trame.jupyter.launch_server>`. |
| 456 |
|
| 457 |
Returns |
| 458 |
------- |
| 459 |
trame_server.core.Server |
| 460 |
The launched trame server. |
| 461 |
|
| 462 |
Warnings |
| 463 |
-------- |
| 464 |
This uses `nest_asyncio <https://github.com/erdewit/nest_asyncio>`_ which |
| 465 |
patches the standard lib `asyncio` package and may have unintended |
| 466 |
consequences for some uses cases. We advise strongly to make sure PyVista's |
| 467 |
Jupyter backend is not set to use Trame when not in a Jupyter environment. |
| 468 |
|
| 469 |
""" |
| 470 |
try: |
| 471 |
import nest_asyncio2 # noqa: PLC0415 |
| 472 |
except ImportError: |
| 473 |
msg = ( |
| 474 |
'Please install `nest_asyncio2` to automagically launch the trame server ' |
| 475 |
'without await. Or, to avoid `nest_asyncio2` run:\n\n' |
| 476 |
'from pyvista.trame.jupyter import launch_server\n' |
| 477 |
'await launch_server().ready' |
| 478 |
) |
| 479 |
raise ImportError(msg) |
| 480 |
|
| 481 |
async def launch_it(): |
| 482 |
await launch_server(*args, **kwargs).ready |
| 483 |
|
| 484 |
# Basically monkey patches asyncio to support this |
| 485 |
nest_asyncio2.apply() |
| 486 |
|
| 487 |
return asyncio.run(launch_it()) |