Python IPython.display.IFrame() Examples

The following are 19 code examples of IPython.display.IFrame(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module IPython.display , or try the search function .
Example #1
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 6 votes vote down vote up
def notebook_correlations(self, col1, col2, width="100%", height=475):
        """
        Helper function to build an `ipython:IPython.display.IFrame` pointing at the correlations popup

        :param col1: column on left side of correlation
        :type col1: str
        :param col2: column on right side of correlation
        :type col2: str
        :param width: width of the ipython cell
        :type width: str or int, optional
        :param height: height of the ipython cell
        :type height: str or int, optional
        :return: :class:`ipython:IPython.display.IFrame`
        """
        self.notebook(
            "/dtale/popup/correlations/",
            params=dict(col1=col1, col2=col2),
            width=width,
            height=height,
        ) 
Example #2
Source File: cloud_logger.py    From retentioneering-tools with Mozilla Public License 2.0 5 votes vote down vote up
def get(self, idx, path=None):
        x = None
        for i in self.fs.find({'filename': idx}):
            x = i.read()
            fmt = i.fmt
        if x is None:
            raise ValueError(f'There is no id in db: {idx}')
        with open((path or '') + idx + '.' + fmt, 'wb') as f:
            f.write(x)
        print(f'Your file saved at {(path or "") + idx + "." + fmt}')
        if fmt == 'png':
            img = mpimg.imread((path or '') + idx + '.' + fmt)
            plt.figure(figsize=[15, 8])
            plt.imshow(img)
            plt.show()
            plt.close()
        elif fmt == 'html':
            html = x.decode()
            width = int(html.split('var width = ')[1].split(',')[0])
            height = int(html.split('height = ')[1].split(';')[0])
            display(IFrame((path or '') + idx + '.' + fmt, width=width + 200, height=height + 200))
        elif fmt == 'json':
            with open((path or '') + idx + '.' + fmt) as f:
                x = json.load(f)
            return x 
Example #3
Source File: tree_selector.py    From retentioneering-tools with Mozilla Public License 2.0 5 votes vote down vote up
def show_tree_filter(event_col, width=500, height=500, **kwargs):
    """
    Shows tree selector for events filtering and aggregation, based on values in ``event_col`` column. It uses `_` for event names splitting, so ideally the event name structure in the dataset should include underscores and have a hierarchical, e.g. ``[section]_[page]_[action]``. In this case event names are separated into levels, so that all the events with the same ``[section]`` will be placed under the same tree node, etc.
    There two kind of checkboxes in tree selector: large blue and small white. The former are used to include or exclude event from original dataset. The latter are used for event aggregation: toggle on a checkbox against an event name level, e.g. a specific ``[section]_[page]``, to aggregate all the underlying events, all the ``[actions]`` in this example, to this level.
    Tree filter has a download button in the end of event list, which downloads a JSON config file, which you then need to use to filter and aggregate events with ``use_tree_filter()`` function.

    Parameters
    --------
    event_col: str
        Column with event names.
    width: int, optional
        Width of IFrame in pixels.
    height: int, optional
        Height of IFrame in pixels.

    Returns
    --------
    Renders events tree selector

    Return type
    --------
    IFrame
    """

    splitted_names = pd.Series(event_col.unique()).str.split('_', expand=True)
    res = _create_node(0, splitted_names, [], '')
    res = __TEMPLATE__.format(tree_data=json.dumps(res))
    with open('./filter.html', 'w') as f:
        f.write(res)
    display(IFrame('./filter.html', width=width, height=height)) 
Example #4
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __str__(self):
        """
        Will try to create an :class:`ipython:IPython.display.IFrame` if being invoked from within ipython notebook
        otherwise simply returns the output of running :meth:`pandas:pandas.DataFrame.__str__` on the data associated
        with this instance

        """
        if in_ipython_frontend():
            self.notebook()
            return ""
        return self.data.__str__() 
Example #5
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __repr__(self):
        """
        Will try to create an :class:`ipython:IPython.display.IFrame` if being invoked from within ipython notebook
        otherwise simply returns the output of running :meth:`pandas:pandas.DataFrame.__repr__` on the data for
        this instance

        """
        if in_ipython_frontend():
            self.notebook()
            if self._notebook_handle is not None:
                return ""
        return self.main_url() 
Example #6
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _build_iframe(
        self, route="/dtale/iframe/", params=None, width="100%", height=475
    ):
        """
        Helper function to build an :class:`ipython:IPython.display.IFrame` if that module exists within
        your environment

        :param route: the :class:`flask:flask.Flask` route to hit on D-Tale
        :type route: str, optional
        :param params: properties & values passed as query parameters to the route
        :type params: dict, optional
        :param width: width of the ipython cell
        :type width: str or int, optional
        :param height: height of the ipython cell
        :type height: str or int, optional
        :return: :class:`ipython:IPython.display.IFrame`
        """
        try:
            from IPython.display import IFrame
        except ImportError:
            logger.info("in order to use this function, please install IPython")
            return None
        iframe_url = "{}{}{}".format(self._url, route, self._data_id)
        if params is not None:
            if isinstance(params, string_types):  # has this already been encoded?
                iframe_url = "{}?{}".format(iframe_url, params)
            else:
                iframe_url = "{}?{}".format(iframe_url, url_encode_func()(params))
        return IFrame(iframe_url, width=width, height=height) 
Example #7
Source File: views.py    From dtale with GNU Lesser General Public License v2.1 5 votes vote down vote up
def notebook(self, route="/dtale/iframe/", params=None, width="100%", height=475):
        """
        Helper function which checks to see if :mod:`flask:flask.Flask` process is up and running and then tries to
        build an :class:`ipython:IPython.display.IFrame` and run :meth:`ipython:IPython.display.display` on it so
        it will be displayed in the ipython notebook which invoked it.

        A reference to the :class:`ipython:IPython.display.DisplayHandle` is stored in _notebook_handle for
        updating if you are running ipython>=5.0

        :param route: the :class:`flask:flask.Flask` route to hit on D-Tale
        :type route: str, optional
        :param params: properties & values passed as query parameters to the route
        :type params: dict, optional
        :param width: width of the ipython cell
        :type width: str or int, optional
        :param height: height of the ipython cell
        :type height: str or int, optional
        """
        try:
            from IPython.display import display
        except ImportError:
            logger.info("in order to use this function, please install IPython")
            return self.data.__repr__()

        retries = 0
        while not self.is_up() and retries < 10:
            time.sleep(0.01)
            retries += 1

        self._notebook_handle = display(
            self._build_iframe(route=route, params=params, width=width, height=height),
            display_id=True,
        )
        if self._notebook_handle is None:
            self._notebook_handle = True 
Example #8
Source File: chartjs_plotter.py    From iplotter with MIT License 5 votes vote down vote up
def plot_and_save(self,
                      data,
                      chart_type,
                      options=None,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """Save the rendered html to a file and return an IFrame to display the plot in the notebook."""
        self.save(data, chart_type, options, filename, w, h, overwrite)
        return IFrame(filename + '.html', w, h) 
Example #9
Source File: google_plotter.py    From iplotter with MIT License 5 votes vote down vote up
def plot_and_save(self,
                      data,
                      chart_type,
                      chart_package='corechart',
                      options=None,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """Save the rendered html to a file and return an IFrame to display the plot in the notebook."""
        self.save(data, chart_type, chart_package, options, filename,
                  overwrite)
        return IFrame(filename + '.html', w, h) 
Example #10
Source File: chartist_plotter.py    From iplotter with MIT License 5 votes vote down vote up
def plot_and_save(self,
                      data,
                      chart_type,
                      options=None,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """Save the rendered html to a file and return an IFrame to display the plot in the notebook."""
        self.save(data, chart_type, options, filename, overwrite)
        return IFrame(filename + '.html', w, h) 
Example #11
Source File: c3_plotter.py    From iplotter with MIT License 5 votes vote down vote up
def plot_and_save(self,
                      data,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """Save the rendered html to a file and returns an IFrame to display the plot in the notebook."""
        self.save(data, filename, overwrite)
        return IFrame(filename + '.html', w, h) 
Example #12
Source File: plotly_plotter.py    From iplotter with MIT License 5 votes vote down vote up
def plot_and_save(self,
                      data,
                      layout=None,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """Save the rendered html to a file and return an IFrame to display the plot in the notebook."""
        self.save(data, layout, filename, overwrite)
        return IFrame(filename + '.html', w, h) 
Example #13
Source File: visualization.py    From finn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def showInNetron(model_filename):
    netron.start(model_filename, port=8081, host="0.0.0.0")
    return IFrame(src="http://0.0.0.0:8081/", width="100%", height=400) 
Example #14
Source File: save_and_load.py    From RFHO with MIT License 5 votes vote down vote up
def save_fig(name, root_dir=None, notebook_mode=True, default_overwrite=False, extension='pdf', **savefig_kwargs):
    if root_dir is None: root_dir = os.getcwd()
    directory = check_or_create_dir(join_paths(root_dir, FOLDER_NAMINGS['PLOTS_DIR']),
                                    notebook_mode=notebook_mode)

    filename = join_paths(directory, '%s.%s' % (name, extension))  # directory + '/%s.pdf' % name
    if not default_overwrite and os.path.isfile(filename):
        # if IPython is not None:
        #     IPython.display.display(tuple(IFrame(filename, width=800, height=600)))  # FIXME not working!
        overwrite = input('A file named %s already exists. Overwrite (Leave string empty for NO!)?' % filename)
        if not overwrite:
            print('No changes done.')
            return
    plt.savefig(filename, **savefig_kwargs)
    # print('file saved') 
Example #15
Source File: tutor_magic.py    From metakernel with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def cell_tutor(self, language=None):
        """
        %%tutor [--language=LANGUAGE] - show cell with 
        Online Python Tutor.

        Defaults to use the language of the current kernel.
        'python' is an alias for 'python3'.

        Examples:
           %%tutor -l python3
           a = 1
           b = 1
           a + b

           [You will see an iframe with the pythontutor.com page 
           including the code above.]

           %%tutor --language=java
           
           public class Test {
               public Test() {
               }
               public static void main(String[] args) {
                   int x = 1;
                   System.out.println("Hi");
               }
           }
        """
        if language is None:
            language = self.kernel.language_info["name"]
        if language not in ['python', 'python2', 'python3', 'java', 'javascript']:
            raise ValueError("{} not supported. Only the following options are allowed: "
                             "'python2', 'python3', 'java', 'javascript'".format(language))
        
        url = "https://pythontutor.com/iframe-embed.html#code="
        url += quote(self.code)
        url += "&origin=opt-frontend.js&cumulative=false&heapPrimitives=false"
        url += "&textReferences=false&"
        if language in ["python3", "python"]:
            url += "py=3&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=350&codeDivHeight=400"
        elif language == "python2":
            url += "py=2&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=350&codeDivHeight=400"
        elif language == "java":
            url += "py=java&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=350&codeDivHeight=400"
        elif language == "javascript":
            url += "py=js&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=350&codeDivHeight=400"

        # Display the results in the output area
        self.kernel.Display(IFrame(url, height=500, width="100%"))
        self.evaluate = False 
Example #16
Source File: document_cluster.py    From TopicNet with MIT License 4 votes vote down vote up
def viev_from_jupyter(
        self,
        dataset,
        method: str = 'TSNE',
        save_path: str = 'DocumentCluster_view.html',
        width: int = 800,
        height: int = 600,
        display_output: bool = True,
        give_html: bool = False,
    ):
        """
        Parameters
        ----------
        dataset: Dataset
        method: string
            any of the methods in sklearn.manifold
        to_html: Bool
            if user wants the plot to be saved in html format
        save_path: str
            save path for the plot requires to be able to create
            the visualisation
        width
            width of the plot in pixels
        height
            height of the plot in pixels
        display_output
            show the plot in the notebook
        give_html
            if return the html string (with javascript) that
            performs the visualisation

        Returns
        -------
        out_html: string
            an html string containing the plotly graph
            returned only if give_html is True

        """
        from IPython.display import IFrame, display_html
        out_html = self.view(
            dataset=dataset,
            save_path=save_path,
            method=method,
            to_html=True,
        )
        if display_output:
            display_html(IFrame(save_path, width=width, height=height))

        if give_html:
            return out_html 
Example #17
Source File: vis_utils.py    From lsm with MIT License 4 votes vote down vote up
def plot_points(xyz,
                colors=None,
                size=0.1,
                axis=False,
                title=None,
                html_out=None):
    positions = xyz.reshape(-1).tolist()
    mkdir_p('vis')
    if html_out is None:
        html_out = os.path.join('vis', 'pts{:s}.html'.format(uuid4()))
    if title is None:
        title = "PointCloud"
    camera_position = xyz.max(0) + abs(xyz.max(0))

    look = xyz.mean(0)

    if colors is None:
        colors = [1, 0.5, 0] * len(positions)

    elif len(colors.shape) > 1:
        colors = colors.reshape(-1).tolist()

    if axis:
        axis_size = xyz.ptp() * 1.5
    else:
        axis_size = 0

    with open(html_out, "w") as html:
        html.write(
            TEMPLATE_POINTS.format(
                title=title,
                camera_x=camera_position[0],
                camera_y=camera_position[1],
                camera_z=camera_position[2],
                look_x=look[0],
                look_y=look[1],
                look_z=look[2],
                positions=positions,
                colors=colors,
                points_size=size,
                axis_size=axis_size))

    return IFrame(html_out, width=1024, height=768) 
Example #18
Source File: threejs_backend.py    From pyntcloud with MIT License 4 votes vote down vote up
def plot_with_threejs(cloud, **kwargs):
    if IFrame is None:
        raise ImportError("IPython is needed for plotting with threejs backend.")

    colors = get_colors(cloud, kwargs["use_as_color"], kwargs["cmap"])

    points = pd.DataFrame(cloud.xyz, columns=["x", "y", "z"])

    for n, i in enumerate(["red", "green", "blue"]):
        points[i] = colors[:, n]

    if kwargs["mesh"] and cloud.mesh is not None:
        mesh = cloud.mesh[["v1", "v2", "v3"]]
    else:
        mesh = None

    ptp = cloud.xyz.ptp()

    BASE_PATH = os.path.dirname(os.path.abspath(__file__))
    src = "{}/{}".format(BASE_PATH, "points.html")
    dst = "{}/{}".format(os.getcwd(), "{}.html".format(kwargs["output_name"]))

    camera_position = (cloud.xyz.max(0) + abs(cloud.xyz.max(0))).tolist()
    look_at = cloud.xyz.mean(0).tolist()

    dest_directory = Path(os.getcwd())
    config_file_path = dest_directory / (kwargs["output_name"] + '.config.json')

    polylines = kwargs["polylines"] or {}
    config_obj = {
        "filename": kwargs["output_name"],
        "camera_position": camera_position,
        "look_at": look_at,
        "point_size": kwargs["initial_point_size"] or ptp / 100,
        "point_opacity": 0.9,
        "polylines_points": list(polylines.values()),
        "polylines_colors": list(polylines.keys()),
    }

    with config_file_path.open('w') as config_file:
        json.dump(config_obj, config_file)

    # write new html file replacing placeholder
    with open(src, "r") as inp, open(dst, "w") as out:
        for line in inp:
            if "FILENAME_PLACEHOLDER" in line:
                line = line.replace("FILENAME_PLACEHOLDER",
                                    "'{}'".format(kwargs["output_name"]))
            out.write(line)

    write_ply("{}.ply".format(kwargs["output_name"]), points=points, mesh=mesh, as_text=True)

    try:
        shutil.copytree("{}/assets".format(BASE_PATH),
                        "{}/{}".format(os.getcwd(), "pyntcloud_plot_assets"))
    except FileExistsError:
        pass

    return IFrame("{}.html".format(kwargs["output_name"]), width=kwargs["width"], height=kwargs["height"]) 
Example #19
Source File: morph_charts.py    From msticpy with MIT License 4 votes vote down vote up
def display(self, data: pd.DataFrame, chart_name: str) -> IFrame:
        """
        Prepare package data and display MorphChart in an IFrame.

        Parameters
        ----------
        data: pd.DataFrame:
            A DataFrame of data for the morphchart to plot.

        chart_name: str:
            The name of the Morph Chart to plot.

        """
        # Check input data is correct format and that the chart being requested exists
        if not isinstance(data, pd.DataFrame):
            raise MsticpyException("Data provided must be in pandas.DataFrame format")

        if chart_name not in self.charts:
            raise MsticpyException(
                f"{chart_name} is not a vaid chart. Run list_charts() to see avaliable charts"  # pylint: disable=line-too-long
            )

        # Create description file with length of our data set
        description_dict = self.charts[chart_name]["DescriptionFile"]
        description_dict["tables"][0]["rows"] = len(data)
        # Create output folder for package files
        out_path = Path.cwd().joinpath(*["morphchart_package", "description.json"])
        Path.mkdir(Path.cwd().joinpath("morphchart_package"), exist_ok=True)
        # Write description file
        morph_file = open(out_path, "w")
        json.dump(description_dict, morph_file)
        # Write dataset to query_data csv
        data_out_path = out_path = Path.cwd().joinpath(
            *["morphchart_package", "query_data.csv"]
        )
        data.to_csv(data_out_path, index=False)
        # Display Morph Charts in IFrame with instructions
        print(
            f"Navigate to {Path.cwd().joinpath('morphchart_package')} and upload the files below"
        )
        print("Charts provided by http://morphcharts.com/")
        return IFrame("http://morphcharts.com/designer.html", "100%", "600px")