Ejemplo n.º 1
0
    def __call__(self, *args, **params):
        # Abort if IPython not found
        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except:
            return

        p = param.ParamOverrides(self, params)
        if hasattr(ip, 'kernel') and not self._loaded:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            JupyterCommManager.get_client_comm(self._process_comm_msg,
                                               "hv-extension-comm")
        _load_nb(p.inline)
        self._loaded = True

        Viewable._comm_manager = JupyterCommManager

        if 'holoviews' in sys.modules:
            import holoviews as hv
            if hv.extension._loaded:
                return
            import holoviews.plotting.bokeh  # noqa
            if hasattr(hv.Store, 'set_current_backend'):
                hv.Store.set_current_backend('bokeh')
            else:
                hv.Store.current_backend = 'bokeh'
Ejemplo n.º 2
0
    def __call__(self, *args, **params):
        # Abort if IPython not found
        for arg in args:
            if arg not in self._imports:
                self.param.warning('%s extension not recognized and '
                                   'will be skipped.' % arg)
            else:
                __import__(self._imports[arg])

        for k, v in params.items():
            if k in ['raw_css', 'css_files']:
                if not isinstance(v, list):
                    raise ValueError('%s should be supplied as a list, '
                                     'not as a %s type.' %
                                     (k, type(v).__name__))
                getattr(config, k).extend(v)
            elif k == 'js_files':
                getattr(config, k).update(v)
            else:
                setattr(config, k, v)

        if config.apply_signatures and sys.version_info.major >= 3:
            self._apply_signatures()

        if 'holoviews' in sys.modules:
            import holoviews as hv
            import holoviews.plotting.bokeh  # noqa
            if not hv.extension._loaded:
                if hasattr(hv.Store, 'set_current_backend'):
                    hv.Store.set_current_backend('bokeh')
                else:
                    hv.Store.current_backend = 'bokeh'

        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except Exception:
            return

        if hasattr(ip,
                   'kernel') and not self._loaded and not config._doc_build:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            _JupyterCommManager.get_client_comm(self._process_comm_msg,
                                                "hv-extension-comm")
            state._comm_manager = _JupyterCommManager

        nb_load = False
        if 'holoviews' in sys.modules:
            if hv.extension._loaded:
                return
            with param.logging_level('ERROR'):
                hv.plotting.Renderer.load_nb(config.inline)
                if hasattr(hv.plotting.Renderer, '_render_with_panel'):
                    nb_load = True

        if not nb_load and hasattr(ip, 'kernel'):
            load_notebook(config.inline)
        panel_extension._loaded = True
Ejemplo n.º 3
0
    def __call__(self, *args, **params):
        # Abort if IPython not found
        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except:
            return

        p = param.ParamOverrides(self, params)
        if hasattr(ip, 'kernel') and not self._loaded:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            JupyterCommManager.get_client_comm(self._process_comm_msg,
                                               "hv-extension-comm")
        _load_nb(p.inline)
        self._loaded = True
        Viewable._comm_manager = JupyterCommManager
Ejemplo n.º 4
0
    def __call__(self, *args, **params):
        # Abort if IPython not found
        for arg in args:
            if arg not in self._imports:
                self.param.warning('%s extension not recognized and '
                                   'will be skipped.' % arg)
            else:
                __import__(self._imports[arg])

        for k, v in params.items():
            if k in ['raw_css', 'css_files']:
                if not isinstance(v, list):
                    raise ValueError('%s should be supplied as a list, '
                                     'not as a %s type.' %
                                     (k, type(v).__name__))
                getattr(config, k).extend(v)
            elif k == 'js_files':
                getattr(config, k).update(v)
            else:
                setattr(config, k, v)

        if config.apply_signatures and sys.version_info.major >= 3:
            self._apply_signatures()

        loaded = self._loaded

        # Short circuit pyvista extension load if VTK is already initialized
        if loaded and args == ('vtk', ) and 'vtk' in self._loaded_extensions:
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 2)
            if len(calframe) >= 3 and 'pyvista' in calframe[2].filename:
                return

        if 'holoviews' in sys.modules:
            import holoviews as hv
            import holoviews.plotting.bokeh  # noqa
            loaded = loaded or getattr(hv.extension, '_loaded', False)

            if hv.Store.current_backend in hv.Store.renderers:
                backend = hv.Store.current_backend
            else:
                backend = 'bokeh'
            if hasattr(hv.Store, 'set_current_backend'):
                hv.Store.set_current_backend(backend)
            else:
                hv.Store.current_backend = backend

        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except Exception:
            return

        newly_loaded = [
            arg for arg in args
            if arg not in panel_extension._loaded_extensions
        ]
        if loaded and newly_loaded:
            self.param.warning(
                "A HoloViz extension was loaded previously. This means "
                "the extension is already initialized and the following "
                "Panel extensions could not be properly loaded: %s. "
                "If you are loading custom extensions with pn.extension(...) "
                "ensure that this is called before any other HoloViz "
                "extension such as hvPlot or HoloViews." % newly_loaded)
        else:
            panel_extension._loaded_extensions += newly_loaded

        if hasattr(ip,
                   'kernel') and not self._loaded and not config._doc_build:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            _JupyterCommManager.get_client_comm(self._process_comm_msg,
                                                "hv-extension-comm")
            state._comm_manager = _JupyterCommManager

        if 'ipywidgets' in sys.modules and config.embed:
            # In embedded mode the ipywidgets_bokeh model must be loaded
            __import__(self._imports['ipywidgets'])

        nb_load = False
        if 'holoviews' in sys.modules:
            if getattr(hv.extension, '_loaded', False):
                return
            with param.logging_level('ERROR'):
                hv.plotting.Renderer.load_nb(config.inline)
                if hasattr(hv.plotting.Renderer, '_render_with_panel'):
                    nb_load = True

        if not nb_load and hasattr(ip, 'kernel'):
            load_notebook(config.inline)
        panel_extension._loaded = True
Ejemplo n.º 5
0
    def __call__(self, *args, **params):
        from .reactive import ReactiveHTML, ReactiveHTMLMetaclass
        reactive_exts = {
            v._extension_name: v
            for k, v in param.concrete_descendents(ReactiveHTML).items()
        }
        for arg in args:
            if arg in self._imports:
                try:
                    if (arg == 'ipywidgets' and get_ipython()
                            and  # noqa (get_ipython)
                            not "PANEL_IPYWIDGET" in os.environ):
                        continue
                except Exception:
                    pass
                __import__(self._imports[arg])
            elif arg in reactive_exts:
                ReactiveHTMLMetaclass._loaded_extensions.add(arg)
            else:
                self.param.warning('%s extension not recognized and '
                                   'will be skipped.' % arg)

        for k, v in params.items():
            if k in ['raw_css', 'css_files']:
                if not isinstance(v, list):
                    raise ValueError('%s should be supplied as a list, '
                                     'not as a %s type.' %
                                     (k, type(v).__name__))
                getattr(config, k).extend(v)
            elif k == 'js_files':
                getattr(config, k).update(v)
            else:
                setattr(config, k, v)

        if config.apply_signatures:
            self._apply_signatures()

        loaded = self._loaded

        # Short circuit pyvista extension load if VTK is already initialized
        if loaded and args == ('vtk', ) and 'vtk' in self._loaded_extensions:
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 2)
            if len(calframe) >= 3 and 'pyvista' in calframe[2].filename:
                return

        if 'holoviews' in sys.modules:
            import holoviews as hv
            import holoviews.plotting.bokeh  # noqa
            loaded = loaded or getattr(hv.extension, '_loaded', False)

            if hv.Store.current_backend in hv.Store.renderers:
                backend = hv.Store.current_backend
            else:
                backend = 'bokeh'
            if hasattr(hv.Store, 'set_current_backend'):
                hv.Store.set_current_backend(backend)
            else:
                hv.Store.current_backend = backend

        # Abort if IPython not found
        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except Exception:
            return

        newly_loaded = [
            arg for arg in args
            if arg not in panel_extension._loaded_extensions
        ]
        if loaded and newly_loaded:
            self.param.warning(
                "A HoloViz extension was loaded previously. This means "
                "the extension is already initialized and the following "
                "Panel extensions could not be properly loaded: %s. "
                "If you are loading custom extensions with pn.extension(...) "
                "ensure that this is called before any other HoloViz "
                "extension such as hvPlot or HoloViews." % newly_loaded)
        else:
            panel_extension._loaded_extensions += newly_loaded

        if hasattr(ip,
                   'kernel') and not self._loaded and not config._doc_build:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            _JupyterCommManager.get_client_comm(self._process_comm_msg,
                                                "hv-extension-comm")
            state._comm_manager = _JupyterCommManager

        if 'ipywidgets' in sys.modules and config.embed:
            # In embedded mode the ipywidgets_bokeh model must be loaded
            __import__(self._imports['ipywidgets'])

        nb_loaded = getattr(self, '_repeat_execution_in_cell', False)
        if 'holoviews' in sys.modules:
            if getattr(hv.extension, '_loaded', False):
                return
            with param.logging_level('ERROR'):
                hv.plotting.Renderer.load_nb(config.inline)
                if hasattr(hv.plotting.Renderer, '_render_with_panel'):
                    nb_loaded = True

        if not nb_loaded and hasattr(ip, 'kernel'):
            load_notebook(config.inline)
        panel_extension._loaded = True

        if 'comms' in params:
            return

        # Try to detect environment so that we can enable comms
        try:
            import google.colab  # noqa
            config.comms = "colab"
            return
        except ImportError:
            pass

        # Check if we're running in VSCode
        if "VSCODE_PID" in os.environ:
            config.comms = "vscode"

        if "pyodide" in sys.modules:
            config.comms = "ipywidgets"

        if config.notifications:
            display(state.notifications)  # noqa
Ejemplo n.º 6
0
    def __call__(self, parameterized, doc=None, plots=[], **params):
        self.p = param.ParamOverrides(self, params)
        if self.p.initializer:
            self.p.initializer(parameterized)

        self._widgets = {}
        self.parameterized = parameterized
        self.document = None
        if self.p.mode == 'notebook':
            if not IPYTHON_AVAILABLE:
                raise ImportError('IPython is not available, cannot use '
                                  'Widgets in notebook mode.')
            self.comm = JupyterCommManager.get_client_comm(on_msg=self.on_msg)
            # HACK: Detects HoloViews plots and lets them handle the comms
            hv_plots = [plot for plot in plots if hasattr(plot, 'comm')]
            self.server_comm = JupyterCommManager.get_server_comm()
            if hv_plots:
                self.document = [p.document for p in hv_plots][0]
                self.p.push = False
            else:
                self.document = doc or Document()
        else:
            self.document = doc or curdoc()
            self.server_comm = None
            self.comm = None

        self._queue = []
        self._active = False
        self._widget_options = {}
        self.shown = False

        # Initialize root container
        widget_box = widgetbox(width=self.p.width)
        view_params = any(isinstance(p, _View) for p in parameterized.params().values())
        layout = self.p.view_position
        container_type = column if layout in ['below', 'above'] else row
        container = container_type() if plots or view_params else widget_box
        self.plot_id = container.ref['id']

        # Initialize widgets and populate container
        widgets, views = self.widgets()
        plots = views + plots
        widget_box.children = widgets

        plots = process_hv_plots(self, plots)

        if plots:
            view_box = column(plots)
            if layout in ['below', 'right']:
                children = [widget_box, view_box]
            else:
                children = [view_box, widget_box]
            container.children = children

        # Initialize view parameters
        for view in views:
            p_obj = self.parameterized.params(view.name)
            value = getattr(self.parameterized, view.name)
            if value is not None:
                rendered = p_obj.renderer(value, p_obj)
                self._update_trait(view.name, rendered)

        # Keeps track of changes between button presses
        self._changed = {}

        if self.p.on_init:
            self.execute()

        if self.p.mode == 'raw':
            return container

        self.document.add_root(container)
        if self.p.mode == 'notebook':
            notebook_show(container, self.document, self.server_comm)
            if self.document._hold is None:
                self.document.hold()
            self.shown = True
            return
        return self.document