"""Function to load plotly layout and configuration from local json file."""
from __future__ import annotations
from json import load
from logging import getLogger
from pathlib import Path
from typing import TYPE_CHECKING
import requests
from requests.exceptions import ConnectionError as RequestsConnectionError
if TYPE_CHECKING:
from .owntypes import CaptorLogoType, PlotlyLayoutType # pragma: no cover
logger = getLogger(__name__)
__all__ = ["load_plotly_dict"]
def _check_remote_file_existence(url: str) -> bool:
"""Check if remote file exists.
Args:
url: Path to remote file.
Returns:
True if url is valid and False otherwise.
"""
ok_code = 200
try:
response = requests.head(url, timeout=30)
if response.status_code != ok_code:
return False
except RequestsConnectionError:
return False
return True
[docs]
def load_plotly_dict(
*,
responsive: bool = True,
) -> tuple[PlotlyLayoutType, CaptorLogoType]:
"""Load Plotly defaults.
Args:
responsive: Flag whether to load as responsive. Defaults to True.
Returns:
tuple[PlotlyLayoutType, CaptorLogoType]: A tuple (config_and_layout, logo)
where config_and_layout is the Plotly config and layout template dict,
and logo is the Captor logo dict (may be empty if the remote logo is
unavailable).
"""
package_dir = Path(__file__).parent
layoutfile = package_dir / "plotly_layouts.json"
logofile = package_dir / "plotly_captor_logo.json"
with layoutfile.open(mode="r", encoding="utf-8") as layout_file:
fig = load(layout_file)
with logofile.open(mode="r", encoding="utf-8") as logo_file:
logo = load(logo_file)
if not _check_remote_file_existence(url=logo["source"]):
msg = f"Failed to add logo image from URL {logo['source']}"
logger.warning(msg)
logo = {}
fig["config"].update({"responsive": responsive})
return fig, logo