Exemplo n.º 1
0
def _bokeh_init():
    io_loop = IOLoop.current()

    server = Server(
        {
            '/_measure':   Application(ScriptHandler(filename='{}/palmar_grip.py'.format(MODELS_PATH))),
            '/_calibre':   Application(ScriptHandler(filename='{}/calibration.py'.format(MODELS_PATH))),
            '/_plot'   :   Application(ScriptHandler(filename='{}/plot_measure.py'.format(MODELS_PATH))),
        },
        io_loop=io_loop,
        allow_websocket_origin=["localhost:5000"]
    )
    server.start()
    io_loop.start()
Exemplo n.º 2
0
def build_single_handler_application(path, argv=None):
    ''' Return a Bokeh application built using a single handler for a script,
    notebook, or directory.

    In general a Bokeh :class:`~bokeh.application.application.Application` may
    have any number of handlers to initialize :class:`~bokeh.document.Document`
    objects for new client sessions. However, in many cases only a single
    handler is needed. This function examines the ``path`` provided, and
    returns an ``Application`` initialized with one of the following handlers:

    * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
      is to a ``.py`` script.

    * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
      ``path`` is to an ``.ipynb`` Jupyter notebook.

    * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
      ``path`` is to a directory containing a ``main.py`` script.

    Args:
        path (str) : path to a file or directory for creating a Bokeh
            application.

        argv (seq[str], optional) : command line arguments to pass to the
            application handler

    Returns:
        :class:`~bokeh.application.application.Application`

    Raises:
        RuntimeError

    Notes:
        If ``path`` ends with a file ``main.py`` then a warning will be printed
        regarding running directory-style apps by passing the directory instead.

    '''
    argv = argv or []
    path = os.path.abspath(path)
    if os.path.isdir(path):
        handler = DirectoryHandler(filename=path, argv=argv)
    else:
        if path.endswith(".ipynb"):
            handler = NotebookHandler(filename=path, argv=argv)
        elif path.endswith(".py"):
            if path.endswith("main.py"):
                warnings.warn(DIRSTYLE_MAIN_WARNING)
            handler = ScriptHandler(filename=path, argv=argv)
        else:
            raise ValueError(
                "Expected a '.py' script or '.ipynb' notebook, got: '%s'" %
                path)

    if handler.failed:
        raise RuntimeError("Error loading %s:\n\n%s\n%s " %
                           (path, handler.error, handler.error_detail))

    application = Application(handler)

    return application
Exemplo n.º 3
0
def build_single_handler_application(path):
    ''' Return a Bokeh application built using a single handler for a file
    or directory.

    Args:
        path (str) : path to a file or directory for creating a Bokeh
            application.

    Returns:
        Application

    Raises:
        RuntimeError

    '''
    path = os.path.abspath(path)
    if os.path.isdir(path):
        handler = DirectoryHandler(filename=path)
    else:
        handler = ScriptHandler(filename=path)

    if handler.failed:
        raise RuntimeError("Error loading %s:\n\n%s\n%s " %
                           (path, handler.error, handler.error_detail))

    application = Application(handler)

    return application
Exemplo n.º 4
0
    def build_applications(self, args):
        if args.files:
            files = args.files
        else:
            files = []

        applications = {}

        for file in files:
            file = os.path.abspath(file)
            if os.path.isdir(file):
                handler = DirectoryHandler(filename=file)
            else:
                handler = ScriptHandler(filename=file)

            if handler.failed:
                die("Error loading %s:\n\n%s\n%s " %
                    (file, handler.error, handler.error_detail))

            application = Application()
            application.add(handler)

            route = handler.url_path()
            if not route:
                if '/' in applications:
                    die("Don't know the URL path to use for %s" % (file))
                route = '/'
            applications[route] = application

        if len(applications) == 0:
            # create an empty application by default, used with output_server typically
            applications['/'] = Application()

        return applications
Exemplo n.º 5
0
def build_single_handler_application(path):
    ''' Return a Bokeh application built using a single handler for a file
    or directory.

    Args:
        path (str) : path to a file or directory for creating a Bokeh
            application.

    Returns:
        Application

    Raises:
        RuntimeError

    '''
    path = os.path.abspath(path)
    if os.path.isdir(path):
        handler = DirectoryHandler(filename=path)
    else:
        if path.endswith(".ipynb"):
            handler = NotebookHandler(filename=path)
        elif path.endswith(".py"):
            handler = ScriptHandler(filename=path)
        else:
            raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path)

    if handler.failed:
        raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail))

    application = Application(handler)

    return application
Exemplo n.º 6
0
def _bokeh_init():
    io_loop = IOLoop.current()

    server = Server(
        {
            '/_address_search':
            Application(ScriptHandler(filename='address_search.py'))
        },
        io_loop=io_loop,
        allow_websocket_origin=["localhost:8080"])
    server.start()
    io_loop.start()
Exemplo n.º 7
0
def main():
    """The pyzebra command line interface.

    This is a wrapper around a bokeh server that provides an interface to launch the application,
    bundled with the pyzebra package.
    """
    app_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app",
                            "app.py")

    parser = argparse.ArgumentParser(
        prog="pyzebra", formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--port",
                        type=int,
                        default=5006,
                        help="port to listen on for HTTP requests")

    parser.add_argument(
        "--allow-websocket-origin",
        metavar="HOST[:PORT]",
        type=str,
        action="append",
        default=None,
        help="hostname that can connect to the server websocket",
    )

    parser.add_argument(
        "--args",
        nargs=argparse.REMAINDER,
        default=[],
        help="command line arguments for the pyzebra application",
    )

    args = parser.parse_args()

    logger.info(app_path)

    handler = ScriptHandler(filename=app_path, argv=args.args)
    server = Server(
        {"/": Application(handler)},
        port=args.port,
        allow_websocket_origin=args.allow_websocket_origin,
    )

    server.start()
    server.io_loop.start()
Exemplo n.º 8
0
def build_single_handler_application(path, argv=None):
    ''' Return a Bokeh application built using a single handler for a file
    or directory.

    Args:
        path (str) : path to a file or directory for creating a Bokeh
            application.
        argv (seq[str], optional) : command line arguments to pass to the
            application handler

    Returns:
        Application

    Raises:
        RuntimeError

    '''
    argv = argv or []
    path = os.path.abspath(path)
    if os.path.isdir(path):
        handler = DirectoryHandler(filename=path, argv=argv)
    else:
        if path.endswith(".ipynb"):
            handler = NotebookHandler(filename=path, argv=argv)
        elif path.endswith(".py"):
            if path.endswith("main.py"):
                warnings.warn(DIRSTYLE_MAIN_WARNING)
            handler = ScriptHandler(filename=path, argv=argv)
        else:
            raise ValueError(
                "Expected a '.py' script or '.ipynb' notebook, got: '%s'" %
                path)

    if handler.failed:
        raise RuntimeError("Error loading %s:\n\n%s\n%s " %
                           (path, handler.error, handler.error_detail))

    application = Application(handler)

    return application
Exemplo n.º 9
0
 def load(filename):
     handler = ScriptHandler(filename=filename)
     handler.modify_document(doc)
     result['handler'] = handler
     result['filename'] = filename
Exemplo n.º 10
0
def main():
    """The streamvis command line interface.

    This is a wrapper around bokeh server that provides an interface to launch
    applications bundled with the streamvis package.
    """
    base_path = os.path.dirname(os.path.abspath(__file__))

    # Discover streamvis apps
    apps_path = os.path.join(base_path, "apps")
    available_apps = []
    for module_info in pkgutil.iter_modules([apps_path]):
        available_apps.append(module_info.name)

    # Prepare argument parser
    parser = argparse.ArgumentParser(
        prog="streamvis", formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")

    parser.add_argument("app", type=str, choices=available_apps, help="streamvis application")

    parser.add_argument(
        "--port", type=int, default=5006, help="a port to listen on for HTTP requests"
    )

    parser.add_argument(
        "--allow-websocket-origin",
        metavar="HOST[:PORT]",
        type=str,
        action="append",
        default=None,
        help="a hostname that can connect to the server websocket",
    )

    parser.add_argument(
        "--page-title", type=str, default="StreamVis", help="browser tab title for the application"
    )

    parser.add_argument(
        "--address",
        metavar="PROTOCOL://HOST:PORT",
        type=str,
        default="tcp://127.0.0.1:9001",
        help="an address string for zmq socket",
    )

    parser.add_argument(
        "--connection-mode",
        type=str,
        choices=["connect", "bind"],
        default="connect",
        help="whether to bind a socket to an address or connect to a remote socket with an address",
    )

    parser.add_argument(
        "--io-threads",
        type=int,
        default=1,
        help="the size of the zmq thread pool to handle I/O operations",
    )

    parser.add_argument(
        "--buffer-size",
        type=int,
        default=1,
        help="a number of last received zmq messages to keep in memory",
    )

    parser.add_argument(
        "--hit-threshold",
        type=int,
        default=15,
        help="a number of spots above which a shot is registered in statistics as 'hit'",
    )

    parser.add_argument(
        "--max-client-connections",
        type=int,
        default=2,
        help="a maximum number of concurrent client connections",
    )

    parser.add_argument(
        "--client-fps", type=float, default=1, help="client update rate in frames per second",
    )

    parser.add_argument(
        "--allow-client-subnet",
        type=str,
        action="append",
        default=None,
        help="a subnet from which client connections are allowed",
    )

    parser.add_argument(
        "--args",
        nargs=argparse.REMAINDER,
        default=[],
        help="command line arguments for the streamvis application",
    )

    args = parser.parse_args()

    app_path = os.path.join(apps_path, args.app + ".py")
    logger.info(app_path)

    # StatisticsHandler is used by Receiver to parse metadata information to be displayed in
    # 'statistics' application, all messages are being processed.
    stats = StatisticsHandler(hit_threshold=args.hit_threshold, buffer_size=args.buffer_size)

    # Receiver gets messages via zmq stream and parses statistics with StatisticsHandler
    receiver = Receiver(on_receive=stats.parse, buffer_size=args.buffer_size)

    # Start receiver in a separate thread
    start_receiver = partial(receiver.start, args.io_threads, args.connection_mode, args.address)
    t = Thread(target=start_receiver, daemon=True)
    t.start()

    # Reconstructs requested images
    jf_adapter = StreamAdapter()

    # StreamvisHandler is a custom bokeh application Handler, which sets some of the core
    # properties for new bokeh documents created by all applications.
    sv_handler = StreamvisHandler(receiver, stats, jf_adapter, args)
    sv_check_handler = StreamvisCheckHandler(
        max_sessions=args.max_client_connections, allow_client_subnet=args.allow_client_subnet
    )

    applications = dict()  # List of bokeh applications

    # Main application
    bokeh_handler = ScriptHandler(filename=app_path, argv=args.args)
    applications["/"] = Application(sv_handler, bokeh_handler, sv_check_handler)

    # Add all common applications
    common_apps_path = os.path.join(base_path, "common_apps")
    for module_info in pkgutil.iter_modules([common_apps_path]):
        app_name = module_info.name
        bokeh_handler = ScriptHandler(filename=os.path.join(common_apps_path, app_name + ".py"))
        sv_check_handler = StreamvisCheckHandler(allow_client_subnet=args.allow_client_subnet)
        applications[f"/{app_name}"] = Application(sv_handler, bokeh_handler, sv_check_handler)

    server = Server(
        applications,
        port=args.port,
        allow_websocket_origin=args.allow_websocket_origin,
        unused_session_lifetime_milliseconds=1,
        check_unused_sessions_milliseconds=3000,
    )

    server.start()
    server.io_loop.start()
Exemplo n.º 11
0
 def load(filename):
     handler = ScriptHandler(filename=filename)
     handler.modify_document(doc)
     result["handler"] = handler
     result["filename"] = filename
Exemplo n.º 12
0
 def load(filename):
     handler = ScriptHandler(filename=filename)
     result['handler'] = handler
     handler.modify_document(doc)
Exemplo n.º 13
0
 def load(filename):
     handler = ScriptHandler(filename=filename)
     handler.modify_document(doc)
     if handler.failed:
         raise RuntimeError(handler.error)
Exemplo n.º 14
0
def build_single_handler_application(path: str,
                                     argv: List[str] | None = None
                                     ) -> Application:
    ''' Return a Bokeh application built using a single handler for a script,
    notebook, or directory.

    In general a Bokeh :class:`~bokeh.application.application.Application` may
    have any number of handlers to initialize |Document| objects for new client
    sessions. However, in many cases only a single handler is needed. This
    function examines the ``path`` provided, and returns an ``Application``
    initialized with one of the following handlers:

    * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
      is to a ``.py`` script.

    * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
      ``path`` is to an ``.ipynb`` Jupyter notebook.

    * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
      ``path`` is to a directory containing a ``main.py`` script.

    Args:
        path (str) : path to a file or directory for creating a Bokeh
            application.

        argv (seq[str], optional) : command line arguments to pass to the
            application handler

    Returns:
        :class:`~bokeh.application.application.Application`

    Raises:
        RuntimeError

    Notes:
        If ``path`` ends with a file ``main.py`` then a warning will be printed
        regarding running directory-style apps by passing the directory instead.

    '''
    argv = argv or []
    path = os.path.abspath(os.path.expanduser(path))
    handler: Handler

    # There are certainly race conditions here if the file/directory is deleted
    # in between the isdir/isfile tests and subsequent code. But it would be a
    # failure if they were not there to begin with, too (just a different error)
    if os.path.isdir(path):
        handler = DirectoryHandler(filename=path, argv=argv)
    elif os.path.isfile(path):
        if path.endswith(".ipynb"):
            handler = NotebookHandler(filename=path, argv=argv)
        elif path.endswith(".py"):
            if path.endswith("main.py"):
                warnings.warn(DIRSTYLE_MAIN_WARNING)
            handler = ScriptHandler(filename=path, argv=argv)
        else:
            raise ValueError(
                "Expected a '.py' script or '.ipynb' notebook, got: '%s'" %
                path)
    else:
        raise ValueError(
            "Path for Bokeh server application does not exist: %s" % path)

    if handler.failed:
        raise RuntimeError("Error loading %s:\n\n%s\n%s " %
                           (path, handler.error, handler.error_detail))

    application = Application(handler)

    return application
def test_missing_filename_raises():
    with pytest.raises(ValueError):
        ScriptHandler()