diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 8e041ae..25c3402 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -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: | @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index dc71b50..9fd0cd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. --- diff --git a/eagleplot/Home.py b/eagleplot/Home.py index e8f86d1..aa962a1 100644 --- a/eagleplot/Home.py +++ b/eagleplot/Home.py @@ -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() diff --git a/eagleplot/plotting.py b/eagleplot/plotting.py index 876ede7..843d9b1 100644 --- a/eagleplot/plotting.py +++ b/eagleplot/plotting.py @@ -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 @@ -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") # ============================================================================ diff --git a/eagleplot/utils/__init__.py b/eagleplot/utils/__init__.py index 6cfb7d0..f0de0ef 100644 --- a/eagleplot/utils/__init__.py +++ b/eagleplot/utils/__init__.py @@ -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 diff --git a/eagleplot/utils/runtime.py b/eagleplot/utils/runtime.py index 61a9664..6c154e2 100644 --- a/eagleplot/utils/runtime.py +++ b/eagleplot/utils/runtime.py @@ -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 diff --git a/eagleplot/utils/session_state.py b/eagleplot/utils/session_state.py index 29237e1..4491dc7 100644 --- a/eagleplot/utils/session_state.py +++ b/eagleplot/utils/session_state.py @@ -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(): @@ -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 @@ -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): @@ -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__'") @@ -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: diff --git a/packaging/web/README.md b/packaging/web/README.md index 1cad886..1d2c9c5 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -124,5 +124,29 @@ the app is up. build also writes `app/404.html` (a copy of `index.html`) for hosts that use the nearest `404.html`, such as Cloudflare Pages. `python -m http.server` has neither: reload from the app root when testing locally. -- **Startup** takes about 15 s on every visit (Python start-up and imports), longer on - the first visit over a slow network. +- **Start-up** (roadmap D4.1). Measured locally (self-hosted Pyodide, no network), the + app is ready in about 7 s: + + | Stage | Time | + | --- | --- | + | Loading Pyodide | ~1.5 s | + | Installing packages (numpy, pandas, matplotlib, Pillow, PyYAML, the wheels) | ~3.2 s | + | Loading Streamlit | ~1.0 s | + | Home.py | ~0.5 s | + + What keeps it there: + - **scipy is not loaded at start-up** (it alone added ~2 s). Home starts loading it in + the background (`eagleplot.utils.runtime.DEFERRED_PACKAGES`); a page that imports it + shows "Loading the science libraries…" until it is there. Home and Quick Plot don't + wait. + - **Home doesn't import pandas** (~2.3 s under Pyodide): `eagleplot.utils` loads its + submodules on first use. After Home is drawn, pandas, matplotlib and the plotting + modules are imported in the background (`runtime.WARM_IMPORTS`), one per event-loop + turn, so a click is handled between two imports. + - **`eagleplot.plotting` imports seaborn and plotly when a plot type needs them**, not + at import. + + Keep it that way: `tests/test_web_build.py` checks that Home doesn't import pandas and + that `eagleplot.plotting` doesn't import seaborn, plotly or scipy. + `node scripts/web/boot_timing.js URL` prints the start-up timeline (cold and warm), and + the docs workflow reports it with the real CDN on every run. diff --git a/packaging/web/build_site.py b/packaging/web/build_site.py index 71d7d3e..ec5fd08 100644 --- a/packaging/web/build_site.py +++ b/packaging/web/build_site.py @@ -44,11 +44,14 @@ APP_PACKAGE = "eagleplot" ENTRYPOINT = f"{APP_PACKAGE}/Home.py" -# Provided by the Pyodide distribution (compiled for WebAssembly). Covers the runtime -# dependencies in pyproject.toml that Pyodide ships: numpy, scipy, pandas, matplotlib, +# Provided by the Pyodide distribution (compiled for WebAssembly) and loaded at start-up: +# the runtime dependencies in pyproject.toml that Pyodide ships, numpy, pandas, matplotlib, # PyYAML and Pillow (Home.py's page icon). tomli is not needed: Pyodide is Python 3.14. +# scipy is NOT loaded at start-up: it alone added ~2 s to every start. It is in +# eagleplot.utils.runtime.DEFERRED_PACKAGES, which Home.py loads in the background once +# the app is up (tests/test_web_build.py keeps the two lists apart). # Optional extras (h5py, xarray, netCDF4, statsmodels) are deliberately not preloaded. -PYODIDE_PACKAGES = ["numpy", "scipy", "pandas", "matplotlib", "pyyaml", "pillow"] +PYODIDE_PACKAGES = ["numpy", "pandas", "matplotlib", "pyyaml", "pillow"] # Pure-Python packages bundled with the site as wheels: the remaining pyproject.toml # dependencies (seaborn, plotly + narwhals, openpyxl + et-xmlfile), and two Streamlit diff --git a/packaging/web/index.html b/packaging/web/index.html index d16c4b6..a40f992 100644 --- a/packaging/web/index.html +++ b/packaging/web/index.html @@ -263,11 +263,20 @@ const splash = window.eaglePlotSplash; const kernel = window.eaglePlotApp._kernel; const STEP_PATTERNS = [/pyodide/i, /install|package/i, /streamlit|server|boot/i]; + // Start-up timeline (ms since page start), for scripts/web/boot_timing.js and the CI + // summary: every kernel progress message, loadFinished and the app being ready. + const bootLog = (window.eaglePlotBootLog = []); + const logBoot = (event, detail) => + bootLog.push({ t: Math.round(performance.now()), event, detail: String(detail ?? "") }); kernel.addEventListener("loadProgress", (e) => { + logBoot("progress", e.detail); const i = STEP_PATTERNS.findIndex((re) => re.test(String(e.detail))); if (i >= 0) splash.setStage(i); }); - kernel.addEventListener("loadFinished", () => splash.setStage(3)); + kernel.addEventListener("loadFinished", () => { + logBoot("loadFinished"); + splash.setStage(3); + }); kernel.addEventListener("loadError", (e) => splash.fail(String(e.detail?.message ?? e.detail ?? ""))); // Hide the splash once the app script has drawn its sidebar. Not on stMain: stlite @@ -276,6 +285,7 @@ if (document.querySelector('[data-testid="stSidebar"]')) { splash.ready(); window.eaglePlotReadyMs = performance.now() - t0; + logBoot("ready"); obs.disconnect(); } }); diff --git a/scripts/web/boot_timing.js b/scripts/web/boot_timing.js new file mode 100644 index 0000000..a8f6f69 --- /dev/null +++ b/scripts/web/boot_timing.js @@ -0,0 +1,108 @@ +// Start-up timing for the in-browser (stlite) EaglePlot build (roadmap D4.1). +// +// node scripts/web/boot_timing.js [URL] [--runs N] [--throttle MBPS,LATENCY_MS] [--out FILE] +// +// URL is the served app (default http://127.0.0.1:8000/app/). Each run opens a fresh browser +// profile (a cold, first visit), waits until the app is ready, then reloads in the same +// profile (a warm visit: the browser cache is kept). For each visit it reports the time to +// "ready" (the sidebar is drawn), the start-up timeline from index.html +// (window.eaglePlotBootLog: stlite's progress messages, loadFinished, ready) and the bytes +// downloaded. --throttle emulates a network, e.g. 20,40 for 20 Mbit/s with 40 ms latency. +// +// Needs Node with the `playwright` package and a Chromium it can launch. +'use strict'; +const fs = require('fs'); +const { chromium } = require('playwright'); + +function parseArgs(argv) { + const opts = { url: 'http://127.0.0.1:8000/app/', runs: 3, throttle: null, out: null }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--runs') opts.runs = Number(argv[++i]); + else if (a === '--throttle') { + const [mbps, latency] = argv[++i].split(',').map(Number); + opts.throttle = { mbps, latency: latency || 0 }; + } else if (a === '--out') opts.out = argv[++i]; + else if (a === '-h' || a === '--help') { + console.log(fs.readFileSync(__filename, 'utf8').split('\n').slice(0, 12).join('\n')); + process.exit(0); + } else if (a.startsWith('--')) throw new Error(`unknown option ${a}`); + else opts.url = a; + } + return opts; +} + +const opts = parseArgs(process.argv.slice(2)); +const median = (xs) => { + const s = [...xs].sort((a, b) => a - b); + return s.length ? s[Math.floor((s.length - 1) / 2)] : null; +}; + +async function visit(page, cdp, reload) { + // Counted from the page's requestfinished events, which include the Web Worker that runs + // Python (Pyodide, packages, wheels); a page-level CDP session would miss those. + let bytes = 0; + let requests = 0; + const pending = []; + const onDone = (req) => { + requests += 1; + pending.push(req.sizes().then((sz) => { bytes += sz.responseBodySize + sz.responseHeadersSize; }).catch(() => {})); + }; + page.on('requestfinished', onDone); + const t0 = Date.now(); + if (reload) await page.reload(); + else await page.goto(opts.url); + await page.waitForFunction(() => (window.eaglePlotBootLog || []).some((e) => e.event === 'ready'), null, { + timeout: 600000, + polling: 100, + }); + const wall = Date.now() - t0; + const log = await page.evaluate(() => window.eaglePlotBootLog); + page.off('requestfinished', onDone); + await Promise.all(pending); + return { wall, readyMs: log.find((e) => e.event === 'ready').t, log, mb: +(bytes / 1e6).toFixed(1), requests }; +} + +(async () => { + const browser = await chromium.launch(); + const results = { url: opts.url, throttle: opts.throttle, cold: [], warm: [] }; + for (let r = 0; r < opts.runs; r++) { + const ctx = await browser.newContext(); + const page = await ctx.newPage(); + const cdp = await ctx.newCDPSession(page); + await cdp.send('Network.enable'); + if (opts.throttle) { + await cdp.send('Network.emulateNetworkConditions', { + offline: false, + latency: opts.throttle.latency, + downloadThroughput: (opts.throttle.mbps * 1e6) / 8, + uploadThroughput: (opts.throttle.mbps * 1e6) / 8, + }); + } + const cold = await visit(page, cdp, false); + const warm = await visit(page, cdp, true); + results.cold.push(cold); + results.warm.push(warm); + console.log(`run ${r + 1}: cold ${(cold.readyMs / 1000).toFixed(1)} s (${cold.mb} MB), ` + + `warm ${(warm.readyMs / 1000).toFixed(1)} s (${warm.mb} MB)`); + await ctx.close(); + } + await browser.close(); + + // Median timeline of the last cold and warm run, as phase durations. + for (const kind of ['cold', 'warm']) { + const runs = results[kind]; + console.log(`\n${kind}: ready median ${(median(runs.map((v) => v.readyMs)) / 1000).toFixed(1)} s, ` + + `downloaded median ${median(runs.map((v) => v.mb))} MB`); + const log = runs[runs.length - 1].log; + let prev = 0; + for (const e of log) { + console.log(` ${String(e.t).padStart(6)} ms +${String(e.t - prev).padStart(5)} ${e.event}${e.detail ? ': ' + e.detail : ''}`); + prev = e.t; + } + } + if (opts.out) fs.writeFileSync(opts.out, JSON.stringify(results, null, 2)); +})().catch((e) => { + console.error('boot timing aborted:', e.message); + process.exit(2); +}); diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 8cd8d62..5b2d8a1 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -244,6 +244,11 @@ def test_home_says_when_it_runs_in_the_browser(monkeypatch, pyodide, desktop, sh AppTest = pytest.importorskip("streamlit.testing.v1").AppTest monkeypatch.setattr(runtime, "IS_PYODIDE", pyodide) monkeypatch.setattr(runtime, "IS_DESKTOP", desktop) + # Home.py starts the deferred package loads in the browser build (D4.1); that is + # covered in tests/test_web_build.py. + monkeypatch.setattr(runtime, "start_deferred_loads", lambda *a: False) + monkeypatch.setattr(runtime, "missing_deferred_packages", lambda *a: []) + monkeypatch.setattr(runtime, "warm_imports_in_background", lambda *a: False) home = Path(__file__).resolve().parent.parent / "eagleplot" / "Home.py" at = AppTest.from_file(str(home), default_timeout=30).run() assert not at.exception diff --git a/tests/test_web_build.py b/tests/test_web_build.py new file mode 100644 index 0000000..cc0888a --- /dev/null +++ b/tests/test_web_build.py @@ -0,0 +1,158 @@ +"""Browser build start-up (roadmap D4.1): scipy is loaded after the app is up, not before.""" + +import importlib.util +import sys +import types +from pathlib import Path + +import pytest + +from eagleplot.utils import runtime + +REPO = Path(__file__).resolve().parent.parent + + +def _build_site(): + spec = importlib.util.spec_from_file_location( + "build_site", REPO / "packaging" / "web" / "build_site.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_deferred_packages_are_not_loaded_at_start_up(): + preloaded = set(_build_site().PYODIDE_PACKAGES) + assert "scipy" in runtime.DEFERRED_PACKAGES + assert not preloaded & set(runtime.DEFERRED_PACKAGES) + # Home.py must not need them: it is what runs while they load. + assert {"numpy", "pandas", "matplotlib"} <= preloaded + + +class _Promise: + """Stands in for the JS promise loadPackage returns; settle() runs its callbacks.""" + + def __init__(self): + self.callbacks = [] + + def then(self, ok, err): + self.callbacks.append(ok) + + def settle(self): + for cb in self.callbacks: + cb(None) + + +class _Calls(list): + promise: "_Promise" + + +@pytest.fixture +def fake_pyodide(monkeypatch): + calls = _Calls() + promise = _Promise() + + def load_package(packages): + calls.append(packages) + return promise + + monkeypatch.setitem(sys.modules, "pyodide_js", types.SimpleNamespace(loadPackage=load_package)) + monkeypatch.setitem( + sys.modules, "pyodide.ffi", types.SimpleNamespace(create_once_callable=lambda f: f) + ) + monkeypatch.setitem(sys.modules, "pyodide", types.SimpleNamespace()) + monkeypatch.setattr(runtime, "IS_PYODIDE", True) + monkeypatch.setattr(runtime, "_deferred_load_started", False) + monkeypatch.setattr(runtime, "_deferred_load_settled", False) + calls.promise = promise + return calls + + +def test_start_deferred_loads_does_nothing_on_a_server(monkeypatch): + monkeypatch.setattr(runtime, "_deferred_load_started", False) + assert runtime.IS_PYODIDE is False + assert runtime.start_deferred_loads() is False + + +def test_start_deferred_loads_starts_once_in_the_browser(fake_pyodide): + assert runtime.start_deferred_loads() is True + assert runtime.start_deferred_loads() is False + assert fake_pyodide == [list(runtime.DEFERRED_PACKAGES)] + + +def test_missing_deferred_packages(): + assert runtime.missing_deferred_packages() == [] # scipy is installed here + assert runtime.missing_deferred_packages(("no_such_package_xyz",)) == ["no_such_package_xyz"] + + +def test_a_deferred_package_counts_as_missing_until_its_load_settles(fake_pyodide): + # scipy's files can be found before its compiled modules are loaded; only the + # settled promise means it can be imported. + runtime.start_deferred_loads() + assert runtime.missing_deferred_packages() == ["scipy"] + fake_pyodide.promise.settle() + assert runtime.missing_deferred_packages() == [] + + +def _home_while_scipy_loads(monkeypatch): + AppTest = pytest.importorskip("streamlit.testing.v1").AppTest + monkeypatch.setattr(runtime, "missing_deferred_packages", lambda packages=(): ["scipy"]) + warm = [] + monkeypatch.setattr(runtime, "warm_imports_in_background", lambda *a: warm.append(1)) + at = AppTest.from_file(str(REPO / "eagleplot" / "Home.py"), default_timeout=60).run() + assert not at.exception + assert warm # Home schedules the background imports + assert not any("Loading the science libraries" in i.value for i in at.info) + return at + + +def test_a_page_opened_before_scipy_arrives_waits_instead_of_failing(fake_pyodide, monkeypatch): + at = _home_while_scipy_loads(monkeypatch) + assert fake_pyodide == [list(runtime.DEFERRED_PACKAGES)] # Home started the load + # Data Upload imports scipy (via eagleplot.math): it waits instead of failing. + next(b for b in at.button if b.key == "home_upload").click().run() + assert not at.exception + assert any("Loading the science libraries" in i.value for i in at.info) + assert not any(t.value == "Data Upload" for t in at.title) + + +def test_quick_plot_does_not_wait_for_scipy(fake_pyodide, monkeypatch): + """Home's one-click example goes straight to a plot: Quick Plot doesn't import scipy.""" + at = _home_while_scipy_loads(monkeypatch) + next(b for b in at.button if b.key == "home_try_sine_cosine_waves.csv").click().run() + assert not at.exception + assert not any("Loading the science libraries" in i.value for i in at.info) + assert any(t.value == "Quick Plot" for t in at.title) + + +def test_plotting_does_not_import_seaborn_plotly_or_scipy(): + """They cost seconds to import in the browser; a Matplotlib plot needs none of them.""" + import subprocess + + code = ( + "import sys, eagleplot.plotting as p; " + "print(sorted(m for m in ('seaborn', 'plotly', 'scipy') if m in sys.modules), " + "p.HAS_SEABORN, p.HAS_PLOTLY)" + ) + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True, cwd=REPO + ).stdout.strip() + assert out == "[] True True" + + +def test_home_does_not_import_pandas(): + """pandas takes ~2.3 s to import in the browser; Home runs before anything else. + + (plotly is not checked: Streamlit itself imports it when it is installed.) + """ + import subprocess + + code = ( + "import sys; from eagleplot.utils import runtime, initialize_session_state, " + "get_session_summary; from eagleplot.utils.theming import app_css; " + "print(sorted(m for m in ('pandas', 'scipy', 'seaborn') if m in sys.modules))" + ) + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True, cwd=REPO + ).stdout.strip() + assert out.splitlines()[-1] == "[]"