예제 #1
0
    def app(self_or_cls,
            plot,
            show=False,
            new_window=False,
            websocket_origin=None):
        """
        Creates a bokeh app from a HoloViews object or plot. By
        default simply attaches the plot to bokeh's curdoc and returns
        the Document, if show option is supplied creates an
        Application instance and displays it either in a browser
        window or inline if notebook extension has been loaded.  Using
        the new_window option the app may be displayed in a new
        browser tab once the notebook extension has been loaded.  A
        websocket origin is required when launching from an existing
        tornado server (such as the notebook) and it is not on the
        default port ('localhost:8888').
        """
        renderer = self_or_cls.instance(mode='server')
        # If show=False and not in notebook context return document
        if not show and not self_or_cls.notebook_context:
            doc, _ = renderer(plot)
            return doc

        def modify_doc(doc):
            renderer(plot, doc=doc)

        handler = FunctionHandler(modify_doc)
        app = Application(handler)

        if not show:
            # If not showing and in notebook context return app
            return app
        elif self_or_cls.notebook_context and not new_window:
            # If in notebook, show=True and no new window requested
            # display app inline
            opts = dict(
                notebook_url=websocket_origin) if websocket_origin else {}
            return bkshow(app, **opts)

        # If app shown outside notebook or new_window requested
        # start server and open in new browser tab
        from tornado.ioloop import IOLoop
        loop = IOLoop.current()
        opts = dict(allow_websocket_origin=[websocket_origin
                                            ]) if websocket_origin else {}
        opts['io_loop' if bokeh_version > '0.12.7' else 'loop'] = loop
        server = Server({'/': app}, port=0, **opts)

        def show_callback():
            server.show('/')

        server.io_loop.add_callback(show_callback)
        server.start()
        try:
            loop.start()
        except RuntimeError:
            pass
        return server
예제 #2
0
    def app(self_or_cls, plot, show=False, new_window=False):
        """
        Creates a bokeh app from a HoloViews object or plot. By
        default simply attaches the plot to bokeh's curdoc and
        returns the Document, if show option is supplied creates
        an Application instance and displays it either in a browser
        window or inline if notebook extension has been loaded.
        Using the new_window option the app may be displayed in a
        new browser tab once the notebook extension has been loaded.
        """
        renderer = self_or_cls.instance(mode='server')
        # If show=False and not in noteboook context return document
        if not show and not self_or_cls.notebook_context:
            doc, _ = renderer(plot)
            return doc

        def modify_doc(doc):
            renderer(plot, doc=doc)

        handler = FunctionHandler(modify_doc)
        app = Application(handler)

        if not show:
            # If not showing and in notebook context return app
            return app
        elif self_or_cls.notebook_context and not new_window:
            # If in notebook, show=True and no new window requested
            # display app inline
            return bkshow(app)

        # If app shown outside notebook or new_window requested
        # start server and open in new browser tab
        from tornado.ioloop import IOLoop
        loop = IOLoop.current()
        server = Server({'/': app}, port=0, loop=loop)

        def show_callback():
            server.show('/')

        server.io_loop.add_callback(show_callback)
        server.start()
        try:
            loop.start()
        except RuntimeError:
            pass
        return server
예제 #3
0
    def app(self_or_cls,
            plot,
            show=False,
            new_window=False,
            websocket_origin=None,
            port=0):
        """
        Creates a bokeh app from a HoloViews object or plot. By
        default simply attaches the plot to bokeh's curdoc and returns
        the Document, if show option is supplied creates an
        Application instance and displays it either in a browser
        window or inline if notebook extension has been loaded.  Using
        the new_window option the app may be displayed in a new
        browser tab once the notebook extension has been loaded.  A
        websocket origin is required when launching from an existing
        tornado server (such as the notebook) and it is not on the
        default port ('localhost:8888').
        """
        if not isinstance(self_or_cls,
                          BokehRenderer) or self_or_cls.mode != 'server':
            renderer = self_or_cls.instance(mode='server')
        else:
            renderer = self_or_cls

        def modify_doc(doc):
            renderer(plot, doc=doc)

        handler = FunctionHandler(modify_doc)
        app = Application(handler)

        if not show:
            # If not showing and in notebook context return app
            return app
        elif self_or_cls.notebook_context and not new_window:
            # If in notebook, show=True and no new window requested
            # display app inline
            if isinstance(websocket_origin, list):
                if len(websocket_origin) > 1:
                    raise ValueError(
                        'In the notebook only a single websocket origin '
                        'may be defined, which must match the URL of the '
                        'notebook server.')
                websocket_origin = websocket_origin[0]
            opts = dict(
                notebook_url=websocket_origin) if websocket_origin else {}
            return bkshow(app, **opts)

        # If app shown outside notebook or new_window requested
        # start server and open in new browser tab
        from tornado.ioloop import IOLoop
        loop = IOLoop.current()
        if websocket_origin and not isinstance(websocket_origin, list):
            websocket_origin = [websocket_origin]
        opts = dict(allow_websocket_origin=websocket_origin
                    ) if websocket_origin else {}
        opts['io_loop'] = loop
        server = Server({'/': app}, port=port, **opts)

        def show_callback():
            server.show('/')

        server.io_loop.add_callback(show_callback)
        server.start()

        def sig_exit(*args, **kwargs):
            loop.add_callback_from_signal(do_stop)

        def do_stop(*args, **kwargs):
            loop.stop()

        signal.signal(signal.SIGINT, sig_exit)
        try:
            loop.start()
        except RuntimeError:
            pass
        return server
예제 #4
0
def main():
    # Parse command line arguments
    parser = argparse.ArgumentParser(
        description='Read an mp3 file and plot out its pitch')
    parser.add_argument('-i',
                        dest='input',
                        type=str,
                        help='Input file path',
                        default='')
    parser.add_argument('-n',
                        dest='normalize',
                        action='store_true',
                        help='Normalize input values',
                        default='')
    parser.add_argument(
        '-t',
        dest='transform',
        type=str,
        help='Use different transforms on the input audio signal',
        default='stft')
    parser.add_argument(
        '-s',
        dest='sample',
        type=int,
        help=
        'Sampling rate in Hz to use on the input audio signal while transforming',
        default='100')
    parser.add_argument(
        '-w',
        dest='window',
        type=float,
        help='Sampling window in s to use on the input audio signal for stft',
        default='0.05')
    options = parser.parse_args()

    # Error check
    if options.input == '':
        print("No input given. BYE!\n")
        return 1
    elif not os.path.isfile(options.input):
        print(f"Given input path {options.input} does not exist!")
        return 2

    # Read input file into frame rate and data
    try:
        inSignal = MP3.read(options.input, options.normalize)
    except:
        print("Reading MP3 failed")
        return 3

    figures = []
    # Plot the data for quick visualization
    if options.transform == 'none':
        for i in range(0, inSignal.channels):
            if i == 0:
                figures.append(
                    bkfigure(plot_width=1200,
                             plot_height=600,
                             x_axis_label='Time',
                             y_axis_label='Amp'))
            else:
                figures.append(
                    bkfigure(plot_width=1200,
                             plot_height=600,
                             x_axis_label='Time',
                             y_axis_label='Amp',
                             x_range=figures[0].x_range,
                             y_range=figures[0].y_range))
            figures[i].line(inSignal.time, inSignal.audioData[:, i])
    elif options.transform == 'stft':
        # STFT over the signal
        fSignal = Transforms.STFT(inSignal,
                                  windowEvery=1 / options.sample,
                                  windowLength=options.window)
        for i in range(0, inSignal.channels):
            if i == 0:
                figures.append(
                    bkfigure(plot_width=1200,
                             plot_height=400,
                             x_axis_label='Time',
                             y_axis_label='Frequency'))
            else:
                figures.append(
                    bkfigure(plot_width=1200,
                             plot_height=400,
                             x_axis_label='Time',
                             y_axis_label='Frequency',
                             x_range=figures[0].x_range,
                             y_range=figures[0].y_range))
            channelAmp = np.max(fSignal.audioData[:, :, i])
            figures[i].image(image=[fSignal.audioData[:, :, i]],
                             x=0,
                             y=0,
                             dw=fSignal.time[-1],
                             dh=fSignal.dimensionAxes[0][-1],
                             color_mapper=LinearColorMapper(high=channelAmp,
                                                            low=0,
                                                            palette=Inferno11))
    else:
        print("Unrecognized transform given!")
        return 4

    bkshow(bkcolumn(*figures))
    return 0
예제 #5
0
    def app(self_or_cls, plot, show=False, new_window=False, websocket_origin=None, port=0):
        """
        Creates a bokeh app from a HoloViews object or plot. By
        default simply attaches the plot to bokeh's curdoc and returns
        the Document, if show option is supplied creates an
        Application instance and displays it either in a browser
        window or inline if notebook extension has been loaded.  Using
        the new_window option the app may be displayed in a new
        browser tab once the notebook extension has been loaded.  A
        websocket origin is required when launching from an existing
        tornado server (such as the notebook) and it is not on the
        default port ('localhost:8888').
        """
        if not isinstance(self_or_cls, BokehRenderer) or self_or_cls.mode != 'server':
            renderer = self_or_cls.instance(mode='server')
        else:
            renderer = self_or_cls

        def modify_doc(doc):
            renderer(plot, doc=doc)
        handler = FunctionHandler(modify_doc)
        app = Application(handler)

        if not show:
            # If not showing and in notebook context return app
            return app
        elif self_or_cls.notebook_context and not new_window:
            # If in notebook, show=True and no new window requested
            # display app inline
            if isinstance(websocket_origin, list):
                if len(websocket_origin) > 1:
                    raise ValueError('In the notebook only a single websocket origin '
                                     'may be defined, which must match the URL of the '
                                     'notebook server.')
                websocket_origin = websocket_origin[0]
            opts = dict(notebook_url=websocket_origin) if websocket_origin else {}
            return bkshow(app, **opts)

        # If app shown outside notebook or new_window requested
        # start server and open in new browser tab
        from tornado.ioloop import IOLoop
        loop = IOLoop.current()
        if websocket_origin and not isinstance(websocket_origin, list):
            websocket_origin = [websocket_origin]
        opts = dict(allow_websocket_origin=websocket_origin) if websocket_origin else {}
        opts['io_loop'] = loop
        server = Server({'/': app}, port=port, **opts)
        def show_callback():
            server.show('/')
        server.io_loop.add_callback(show_callback)
        server.start()

        def sig_exit(*args, **kwargs):
            loop.add_callback_from_signal(do_stop)

        def do_stop(*args, **kwargs):
            loop.stop()

        signal.signal(signal.SIGINT, sig_exit)
        try:
            loop.start()
        except RuntimeError:
            pass
        return server