Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ jobs:
for i in $(seq 1 30); do curl -sf localhost:8000/app/ >/dev/null && break; sleep 1; done
node scripts/web/smoke.js http://127.0.0.1:8000/app/ --out build/web-smoke

# Start-up time with the real Pyodide CDN (roadmap D4): a fresh profile (first visit),
# then a reload with the cache kept. Reported in the summary; it doesn't gate.
- name: Measure start-up
continue-on-error: true
run: node scripts/web/boot_timing.js http://127.0.0.1:8000/app/ --runs 3 --out build/web-smoke/boot.json | tee build/web-smoke/boot.txt

- name: Summary
if: always()
run: |
Expand All @@ -112,6 +118,11 @@ jobs:
print()
print("Requests by origin: " + ", ".join(f"{o} ({n})" for o, n in s["origins"].items()))
PY
echo
echo "## Start-up time (Pyodide from the CDN)"
echo '```'
cat build/web-smoke/boot.txt 2>/dev/null || echo "(not measured)"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"

- uses: actions/upload-artifact@v7
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
only on a first visit. If loading fails, the screen says why and offers **Reload**
instead of sliding forever. With reduced motion turned on in the system settings, the
logo appears complete and nothing moves.
- **The web app starts faster:** ready in about 7 s instead of 11 s (measured on a fast
local connection), and the first plot from Home ("Plot this example") appears about 4 s
sooner. scipy is loaded in the background after the app appears, and pandas and the
plotting libraries are imported while you read the Home page. A page that needs scipy
says so for a moment if you open it within the first seconds.
- Importing `eagleplot.plotting` no longer imports seaborn, plotly or scipy (they load when
a plot type needs them), and importing `eagleplot.utils` no longer imports pandas. This
also makes the installed GUI start a little faster.

---

Expand Down
24 changes: 24 additions & 0 deletions eagleplot/Home.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,4 +421,28 @@ def _home_page() -> None:

# ── Execute the active page ───────────────────────────────────────────────────


def _wait_for_deferred_packages() -> None:
"""Browser build: tell the user the page is waiting, and rerun once it can load."""
st.info("Loading the science libraries for this page (only once per visit)…")

@st.fragment(run_every=0.5)
def _poll() -> None:
if not runtime.missing_deferred_packages():
st.rerun(scope="app")

_poll()


if runtime.IS_PYODIDE:
# The browser build starts without scipy (roadmap D4.1): load it now, while the
# student looks at Home, and hold other pages until it is there.
runtime.start_deferred_loads()
# …and import pandas and the plotting stack while the student reads Home.
runtime.warm_imports_in_background()
# Home and Quick Plot don't import them; scipy-based plot types import it when used.
if pg not in (home_pg, basic_pg) and runtime.missing_deferred_packages():
_wait_for_deferred_packages()
st.stop()

pg.run()
40 changes: 29 additions & 11 deletions eagleplot/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import matplotlib.colors as mcolors
from matplotlib.figure import Figure
from matplotlib.axes import Axes
import importlib.util as _importlib_util
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast

Expand All @@ -35,20 +36,37 @@
"#000000", # black
]

# Optional imports for advanced features
try:
import seaborn as sns
# Optional imports for advanced features. Checked here, imported on first use: seaborn
# (which pulls in scipy) and plotly take seconds to import in the browser build, and a
# Matplotlib line plot needs neither (roadmap D4.1).


class _LazyModule:
"""Imports *name* the first time one of its attributes is used."""

def __init__(self, name: str) -> None:
self._name = name
self._module: Any = None

def __getattr__(self, attr: str) -> Any:
if self._module is None:
import importlib

self._module = importlib.import_module(self._name)
return getattr(self._module, attr)


HAS_SEABORN = True
except ImportError:
HAS_SEABORN = False
def _installed(name: str) -> bool:
try:
return _importlib_util.find_spec(name) is not None
except (ImportError, ValueError):
return False

try:
import plotly.graph_objects as go

HAS_PLOTLY = True
except ImportError:
HAS_PLOTLY = False
HAS_SEABORN = _installed("seaborn")
HAS_PLOTLY = _installed("plotly")
sns: Any = _LazyModule("seaborn")
go: Any = _LazyModule("plotly.graph_objects")


# ============================================================================
Expand Down
93 changes: 57 additions & 36 deletions eagleplot/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,64 @@
"""Utility modules for Streamlit GUI."""

from .session_state import (
initialize_session_state,
add_dataset,
get_current_dataset,
get_dataset,
delete_dataset,
add_plot_to_history,
clear_plot_history,
add_analysis_result,
save_session_to_file,
load_session_from_file,
clear_session,
get_session_summary,
)
# The names below are loaded from their submodules on first use (PEP 562), not when the
# package is imported. Importing session_state or data_preview pulls in pandas, which takes
# ~2.3 s in the browser build; Home and small helpers (``eagleplot.utils.runtime`` …) must
# not pay that at start-up (roadmap D4.1). ``from eagleplot.utils import X`` works as before.
_EXPORTS = {
"session_state": (
"initialize_session_state",
"add_dataset",
"get_current_dataset",
"get_dataset",
"delete_dataset",
"add_plot_to_history",
"clear_plot_history",
"add_analysis_result",
"save_session_to_file",
"load_session_from_file",
"clear_session",
"get_session_summary",
),
"data_preview": (
"preview_dataframe",
"get_dataframe_info",
"get_array_info",
"format_data_size",
"display_dataset_card",
"get_column_suggestions",
"display_data_preview",
"get_plottable_arrays",
),
"user_settings": (
"get_config_path",
"load_config",
"save_config",
"get_defaults",
"save_defaults",
"list_presets",
"save_preset",
"load_preset",
"delete_preset",
"SAVEABLE_KEYS",
),
}
_MODULE_OF = {name: module for module, names in _EXPORTS.items() for name in names}

from .data_preview import (
preview_dataframe,
get_dataframe_info,
get_array_info,
format_data_size,
display_dataset_card,
get_column_suggestions,
display_data_preview,
get_plottable_arrays,
)

from .user_settings import (
get_config_path,
load_config,
save_config,
get_defaults,
save_defaults,
list_presets,
save_preset,
load_preset,
delete_preset,
SAVEABLE_KEYS,
)
def __getattr__(name):
module = _MODULE_OF.get(name)
if module is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
import importlib

value = getattr(importlib.import_module(f"{__name__}.{module}"), name)
globals()[name] = value # later lookups skip __getattr__
return value


def __dir__():
return sorted(set(globals()) | set(_MODULE_OF))


__all__ = [
# Session state
Expand Down
102 changes: 102 additions & 0 deletions eagleplot/utils/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,105 @@ def missing_package_message(message: str, caps: Capabilities | None = None) -> s
f"install EaglePlot on your computer (`pip install eagleplot`), then `pip install "
f"{packages}`."
)


# ── Packages loaded after start-up (browser build, roadmap D4.1) ───────────────
#: Not loaded when the browser build starts: scipy alone added ~2 s to every start, and
#: the Home page doesn't need it. The build (packaging/web/build_site.py) leaves these
#: out; Home.py starts loading them in the background as soon as the app is up, and other
#: pages wait for them (see ``missing_deferred_packages``).
DEFERRED_PACKAGES = ("scipy",)

_deferred_load_started = False
#: Set when Pyodide's loadPackage promise settles. Until then a deferred package can be
#: half there: its files unpacked (so ``find_spec`` finds it) but its compiled modules not
#: loaded yet, and importing it fails with "dynamic module does not define module export
#: function" (seen with scipy.spatial).
_deferred_load_settled = False


def _mark_deferred_load_settled(*_args) -> None:
global _deferred_load_settled
_deferred_load_settled = True


def start_deferred_loads(packages: tuple = DEFERRED_PACKAGES) -> bool:
"""Under Pyodide, start loading *packages* in the background (once per process).

Returns ``True`` if this call started the load. Elsewhere it does nothing: on a
server every package is installed already.
"""
global _deferred_load_started
if not IS_PYODIDE or _deferred_load_started:
return False
import pyodide_js # type: ignore[import-not-found] # only exists under Pyodide
from pyodide.ffi import create_once_callable # type: ignore[import-not-found]

# A JS promise, not awaited, so the page carries on while the packages load. Both
# outcomes settle it: after a failed load, pages report the import error instead of
# waiting for ever.
promise = pyodide_js.loadPackage(list(packages))
promise.then(
create_once_callable(_mark_deferred_load_settled),
create_once_callable(_mark_deferred_load_settled),
)
_deferred_load_started = True
return True


def missing_deferred_packages(packages: tuple = DEFERRED_PACKAGES) -> list:
"""The *packages* that pages can't import yet (always empty on a server).

Under Pyodide that is all of them until their load has finished.
"""
if IS_PYODIDE and _deferred_load_started and not _deferred_load_settled:
return list(packages)
import importlib
import importlib.util

importlib.invalidate_caches()
return [p for p in packages if importlib.util.find_spec(p) is None]


#: Imported in the background after Home is drawn (browser build), in this order, so the
#: first visit to a data page doesn't pay for them: pandas alone takes ~2.3 s to import
#: under Pyodide, and the plotting stack (matplotlib, seaborn, plotly) several more.
#: The ``eagleplot.*`` entries need the deferred packages, so they wait for those.
WARM_IMPORTS = ("pandas", "matplotlib.pyplot", "eagleplot.plotting", "eagleplot.math")

_warm_imports_started = False


def warm_imports_in_background(modules: tuple = WARM_IMPORTS, delay: float = 0.5) -> bool:
"""Under Pyodide, import *modules* one by one once the event loop is idle.

Python runs on one thread in the browser, so each import still blocks while it runs;
doing them one per loop turn lets a click be handled between two imports. A module
that fails to import is skipped (the page that needs it reports the error).
Returns ``True`` if this call scheduled the imports; elsewhere it does nothing.
"""
global _warm_imports_started
if not IS_PYODIDE or _warm_imports_started:
return False
import asyncio
import importlib

loop = asyncio.get_event_loop()
queue = list(modules)

def step() -> None:
if not queue:
return
if queue[0].startswith("eagleplot.") and missing_deferred_packages():
loop.call_later(0.25, step) # wait for scipy & co.
return
name = queue.pop(0)
try:
importlib.import_module(name)
except Exception: # noqa: BLE001 - reported by the page that imports it
pass
loop.call_later(0.05, step)

loop.call_later(delay, step)
_warm_imports_started = True
return True
21 changes: 18 additions & 3 deletions eagleplot/utils/session_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,20 @@
>>> dataset = get_current_dataset()
"""

from __future__ import annotations

import io
import streamlit as st
import json
import base64
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
import numpy as np
import pandas as pd
from typing import TYPE_CHECKING, Any, Dict, List, Optional

# numpy and pandas are imported inside the functions that use them: Home.py imports this
# module, and pandas alone takes ~2.3 s to import in the browser build (roadmap D4.1).
if TYPE_CHECKING:
import numpy as np


def initialize_session_state():
Expand Down Expand Up @@ -102,6 +107,9 @@ def add_dataset(name: str, data: Any, metadata: Optional[Dict] = None):
metadata : dict, optional
Additional metadata (file size, upload time, etc.)
"""
import numpy as np
import pandas as pd

st.session_state.datasets[name] = data

# Store metadata
Expand Down Expand Up @@ -275,6 +283,9 @@ def _serialize_data(data: Any) -> Any:
deliberately not used here. Object-dtype arrays are also refused, since
their contents cannot be represented without pickling.
"""
import numpy as np
import pandas as pd

if isinstance(data, pd.DataFrame):
return {"__type__": "DataFrame", "__data__": data.to_json(orient="split")}
elif isinstance(data, np.ndarray):
Expand Down Expand Up @@ -324,6 +335,8 @@ def _decode_ndarray(data: Dict) -> np.ndarray:
If the dtype is absent, is an object dtype, or if the decoded buffer
length does not match ``dtype.itemsize * prod(shape)``.
"""
import numpy as np

dtype_str = data.get("__dtype__")
if not dtype_str:
raise ValueError("ndarray entry is missing '__dtype__'")
Expand Down Expand Up @@ -373,6 +386,8 @@ def _deserialize_data(data: Any, skipped: Optional[List[str]] = None) -> Any:
(``__type__`` of ``"pickled"``, and ``"ndarray"`` without a ``__dtype__``).
Those are refused rather than unpickled — see :func:`_serialize_data`.
"""
import pandas as pd

if isinstance(data, dict):
kind = data.get("__type__")
if kind is None:
Expand Down
Loading
Loading