Skip to content

Commit

Permalink
feat(maidr.show): use tempfile for interactive sessions (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
dakshpokar authored Oct 15, 2024
1 parent 4bb9e77 commit ef668ee
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
22 changes: 20 additions & 2 deletions maidr/core/maidr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import io
import json
import os
import tempfile
import uuid
import webbrowser
from typing import Literal

from htmltools import HTML, HTMLDocument, Tag, tags
Expand Down Expand Up @@ -83,8 +86,11 @@ def show(self, renderer: Literal["auto", "ipython", "browser"] = "auto") -> obje
The renderer to use for the HTML preview.
"""
html = self._create_html_tag()
if Environment.is_interactive_shell() and not Environment.is_notebook():
return html.show("browser")
_renderer = Environment.get_renderer()
if _renderer == "browser" or (
Environment.is_interactive_shell() and not Environment.is_notebook()
):
return self._open_plot_in_browser()
return html.show(renderer)

def clear(self):
Expand All @@ -94,6 +100,18 @@ def destroy(self) -> None:
del self._plots
del self._fig

def _open_plot_in_browser(self) -> None:
"""
Open the rendered HTML content using a temporary file
"""
system_temp_dir = tempfile.gettempdir()
static_temp_dir = os.path.join(system_temp_dir, "maidr")
os.makedirs(static_temp_dir, exist_ok=True)

temp_file_path = os.path.join(static_temp_dir, "maidr_plot.html")
html_file_path = self.save_html(temp_file_path)
webbrowser.open(f"file://{html_file_path}")

def _create_html_tag(self) -> Tag:
"""Create the MAIDR HTML using HTML tags."""
tagged_elements = [element for plot in self._plots for element in plot.elements]
Expand Down
14 changes: 14 additions & 0 deletions maidr/util/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ def is_notebook() -> bool:
except ImportError:
return False

@staticmethod
def get_renderer() -> str:
"""Return renderer which can be ipython or browser."""
try:
import IPython # pyright: ignore[reportUnknownVariableType]

ipy = ( # pyright: ignore[reportUnknownVariableType]
IPython.get_ipython() # pyright: ignore[reportUnknownMemberType, reportPrivateImportUsage]
)
renderer = "ipython" if ipy else "browser"
except ImportError:
renderer = "browser"
return renderer

@staticmethod
def initialize_llm_secrets(unique_id: str) -> str:
"""Inject the LLM API keys into the MAIDR instance."""
Expand Down

0 comments on commit ef668ee

Please sign in to comment.