PyMieSimX 0.4.8__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. pymiesimx-0.5.0/PKG-INFO +198 -0
  2. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/_version.py +1 -1
  3. pymiesimx-0.5.0/PyMieSimX/gui/admin.py +242 -0
  4. pymiesimx-0.5.0/PyMieSimX/gui/assets/admin-activity.css +66 -0
  5. pymiesimx-0.5.0/PyMieSimX/gui/assets/admin-login.css +32 -0
  6. pymiesimx-0.5.0/PyMieSimX/gui/assets/amsterdam-umc-flower.svg +11 -0
  7. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/dashboard.css +138 -196
  8. pymiesimx-0.5.0/PyMieSimX/gui/assets/logo.png +0 -0
  9. pymiesimx-0.5.0/PyMieSimX/gui/assets/pymiesim-favicon.svg +1 -0
  10. pymiesimx-0.5.0/PyMieSimX/gui/assets/pymiesim-logo-dark.svg +8 -0
  11. pymiesimx-0.5.0/PyMieSimX/gui/assets/pymiesim-logo.svg +8 -0
  12. pymiesimx-0.5.0/PyMieSimX/gui/assets/sidebar-dismiss.js +17 -0
  13. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/callbacks.py +39 -157
  14. pymiesimx-0.5.0/PyMieSimX/gui/components/run_toolbar.py +34 -0
  15. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/computation.py +76 -45
  16. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/interface.py +13 -1
  17. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/jobs.py +28 -12
  18. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/layout.py +36 -5
  19. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/documentation.py +0 -8
  20. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/examples.py +59 -40
  21. pymiesimx-0.5.0/PyMieSimX/gui/pages/experiment/callbacks.py +142 -0
  22. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/experiment/page.py +3 -27
  23. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/home.py +31 -75
  24. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/population.py +4 -15
  25. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/single/page.py +2 -21
  26. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/seo.py +1 -1
  27. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/usage_metrics.py +52 -0
  28. pymiesimx-0.5.0/PyMieSimX/gui/visit_location.py +55 -0
  29. pymiesimx-0.5.0/PyMieSimX.egg-info/PKG-INFO +198 -0
  30. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX.egg-info/SOURCES.txt +7 -0
  31. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX.egg-info/requires.txt +4 -7
  32. pymiesimx-0.5.0/README.rst +159 -0
  33. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/pyproject.toml +13 -13
  34. pymiesimx-0.4.8/PKG-INFO +0 -279
  35. pymiesimx-0.4.8/PyMieSimX/gui/admin.py +0 -122
  36. pymiesimx-0.4.8/PyMieSimX/gui/assets/logo.png +0 -0
  37. pymiesimx-0.4.8/PyMieSimX/gui/assets/pymiesim-favicon.svg +0 -6
  38. pymiesimx-0.4.8/PyMieSimX/gui/assets/pymiesim-logo-dark.svg +0 -15
  39. pymiesimx-0.4.8/PyMieSimX/gui/assets/pymiesim-logo.svg +0 -39
  40. pymiesimx-0.4.8/PyMieSimX.egg-info/PKG-INFO +0 -279
  41. pymiesimx-0.4.8/README.rst +0 -238
  42. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/LICENSE +0 -0
  43. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/__init__.py +0 -0
  44. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/__main__.py +0 -0
  45. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/api.py +0 -0
  46. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/application/__init__.py +0 -0
  47. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/application/wsgi.py +0 -0
  48. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/__init__.py +0 -0
  49. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/card-state.js +0 -0
  50. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/default-settings.json +0 -0
  51. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/home-spf-radial.gif +0 -0
  52. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/home-spf-radial.png +0 -0
  53. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/materials-stock.json +0 -0
  54. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/assets/simulation-sharing.js +0 -0
  55. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/callback_helpers.py +0 -0
  56. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/components/__init__.py +0 -0
  57. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/components/cards.py +0 -0
  58. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/defaults.py +0 -0
  59. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/experiment_service.py +0 -0
  60. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/material_catalog.py +0 -0
  61. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/models.py +0 -0
  62. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/__init__.py +0 -0
  63. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/citation.py +0 -0
  64. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/experiment/__init__.py +0 -0
  65. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/experiment/sections/__init__.py +0 -0
  66. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/experiment/sections/configuration.py +0 -0
  67. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/field_syntax.py +0 -0
  68. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/install_local.py +0 -0
  69. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/sellmeier.py +0 -0
  70. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/settings.py +0 -0
  71. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/single/__init__.py +0 -0
  72. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/single/sections/__init__.py +0 -0
  73. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/single/sections/representations.py +0 -0
  74. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/pages/single/sections/setup.py +0 -0
  75. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/parsing.py +0 -0
  76. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/plotting.py +0 -0
  77. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/population_service.py +0 -0
  78. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/schemas.py +0 -0
  79. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/services.py +0 -0
  80. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/sharing.py +0 -0
  81. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/single_service.py +0 -0
  82. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX/gui/validation.py +0 -0
  83. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX.egg-info/dependency_links.txt +0 -0
  84. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX.egg-info/entry_points.txt +0 -0
  85. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/PyMieSimX.egg-info/top_level.txt +0 -0
  86. {pymiesimx-0.4.8 → pymiesimx-0.5.0}/setup.cfg +0 -0
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: PyMieSimX
3
+ Version: 0.5.0
4
+ Summary: Interactive Mie scattering simulations for individual particles, parameter sweeps, and dilute particle populations.
5
+ Author-email: Martin Poinsinet de Sivry-Houle <martin.poinsinet.de.sivry@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://martinpdes.github.io/PyMieSimX/
8
+ Project-URL: Repository, https://github.com/MartinPdeS/PyMieSimX
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/x-rst
15
+ License-File: LICENSE
16
+ Requires-Dist: PyMieSim<6,>=5.7.1
17
+ Requires-Dist: PyOptik<4,>=3.2.1
18
+ Requires-Dist: dash<5,>=4.1.0
19
+ Requires-Dist: itsdangerous<3,>=2.1
20
+ Requires-Dist: gunicorn<24,>=23.0.0
21
+ Requires-Dist: numpy<3,>=2.0
22
+ Requires-Dist: pandas<3,>=2.2
23
+ Requires-Dist: pint<0.26,>=0.24
24
+ Requires-Dist: plotly<7,>=5.24
25
+ Requires-Dist: psycopg[binary]<4,>=3.2.9
26
+ Provides-Extra: release
27
+ Requires-Dist: martinpdes-maintenance==0.2.3; extra == "release"
28
+ Provides-Extra: testing
29
+ Requires-Dist: martinpdes-maintenance[testing]==0.2.3; extra == "testing"
30
+ Provides-Extra: browser
31
+ Requires-Dist: dash[testing]<5,>=4.1; extra == "browser"
32
+ Provides-Extra: dev
33
+ Requires-Dist: martinpdes-maintenance[quality]==0.2.3; extra == "dev"
34
+ Provides-Extra: docs
35
+ Requires-Dist: MartinPdeS-docs<0.5,>=0.4.0; extra == "docs"
36
+ Provides-Extra: documentation
37
+ Requires-Dist: MartinPdeS-docs<0.5,>=0.4.0; extra == "documentation"
38
+ Dynamic: license-file
39
+
40
+ PyMieSimX
41
+ =========
42
+
43
+ .. image:: https://raw.githubusercontent.com/MartinPdeS/PyMieSimX/HEAD/docs/source/_static/logo.svg
44
+ :alt: PyMieSimX logo
45
+ :width: 100%
46
+
47
+ .. list-table::
48
+ :width: 100%
49
+ :widths: 35 65
50
+ :header-rows: 1
51
+
52
+ * - Badge
53
+ - Status
54
+ * - Web app
55
+ - |mps-demo|
56
+ * - Python versions
57
+ - |mps-python|
58
+ * - Documentation
59
+ - |mps-docs|
60
+ * - Tests
61
+ - |mps-ci| |mps-coverage|
62
+ * - PyPI
63
+ - |mps-pypi| |mps-downloads|
64
+ * - Conda
65
+ - |mps-conda| |mps-conda-downloads| |mps-conda-release|
66
+
67
+ Interactive Mie scattering simulations for individual particles, parameter sweeps, and dilute particle populations.
68
+
69
+ Explore how particle size, composition, and illumination change scattering with
70
+ `PyMieSim <https://github.com/MartinPdeS/PyMieSim>`_. Open a setup from the
71
+ **Examples** page, adjust its inputs, and select **Run**.
72
+
73
+ * **Single Scatterer** shows the angular scattering, polarization, and fields of one particle.
74
+ * **Parameter Scan** sweeps source, scatterer, or detector parameters and compares the resulting measures.
75
+ * **Ensemble Optics** averages optical properties over a dilute population of spheres with a chosen size distribution and concentration.
76
+
77
+ Export results as CSV or use **Copy simulation link** to share the setup.
78
+ Opening a shared link reruns it with the receiving installation's solver and material data.
79
+
80
+ To run locally after installation, launch ``pymiesimx``. The first launch downloads
81
+ PyOptik's refractive-index catalogue.
82
+
83
+ .. figure:: https://raw.githubusercontent.com/MartinPdeS/PyMieSimX/HEAD/docs/source/_static/app-screenshot.png
84
+
85
+ PyMieSimX home page with the Single Scatterer and Parameter Scan workspaces.
86
+
87
+ Installation
88
+ ------------
89
+
90
+ Requires Python ``>=3.11``.
91
+
92
+ .. code-block:: console
93
+
94
+ $ python -m pip install PyMieSimX
95
+
96
+ Install from the ``martinpdes`` Conda channel:
97
+
98
+ .. code-block:: console
99
+
100
+ $ conda install -c martinpdes pymiesimx
101
+
102
+ For an editable source installation:
103
+
104
+ .. code-block:: console
105
+
106
+ $ git clone https://github.com/MartinPdeS/PyMieSimX.git
107
+ $ cd PyMieSimX
108
+ $ python -m pip install -e .
109
+
110
+ Calculate scattering efficiency in Python
111
+ -----------------------------------------
112
+
113
+ Compute the scattering efficiency of a 500 nm sphere at a wavelength of 650 nm.
114
+ With these inputs, the dimensionless scattering efficiency is approximately 1.629.
115
+
116
+ .. code-block:: python
117
+
118
+ """Calculate the scattering efficiency of a single sphere."""
119
+
120
+ from PyMieSimX import run_experiment
121
+
122
+ result = run_experiment(
123
+ source_type="GaussianSet",
124
+ source_values={
125
+ "wavelength": "650",
126
+ "polarization": "0",
127
+ "optical_power": "1e-3",
128
+ "numerical_aperture": "0.2",
129
+ },
130
+ scatterer_type="SphereSet",
131
+ scatterer_values={"diameter": "500", "material": "1.4", "medium": "1.0"},
132
+ detector_type="None",
133
+ detector_values={},
134
+ measure="Qsca",
135
+ )
136
+ print(result["rows"][0]["Qsca"])
137
+
138
+ Documentation
139
+ -------------
140
+
141
+ Use the `PyMieSimX documentation <https://martinpdes.github.io/PyMieSimX/>`__ to work through
142
+ examples and look up the inputs and return values of individual functions.
143
+
144
+ Contributing
145
+ ------------
146
+
147
+ Bug reports, worked examples, and documentation corrections are welcome.
148
+ To set up a development checkout and run the tests, follow the `contributing guide <https://github.com/MartinPdeS/PyMieSimX/blob/HEAD/CONTRIBUTING.md>`__.
149
+
150
+ Contact
151
+ -------
152
+
153
+ For questions, contact `Martin Poinsinet de Sivry-Houle <mailto:martin.poinsinet.de.sivry@gmail.com?subject=PyMieSimX>`__.
154
+
155
+ License
156
+ -------
157
+
158
+ PyMieSimX is licensed under `MIT <https://github.com/MartinPdeS/PyMieSimX/blob/HEAD/LICENSE>`__.
159
+
160
+ .. |mps-python| image:: https://img.shields.io/pypi/pyversions/pymiesimx.svg
161
+ :alt: Supported Python versions
162
+ :target: https://pypi.org/project/pymiesimx/
163
+
164
+ .. |mps-pypi| image:: https://img.shields.io/pypi/v/pymiesimx.svg
165
+ :alt: PyPI version
166
+ :target: https://pypi.org/project/pymiesimx/
167
+
168
+ .. |mps-downloads| image:: https://img.shields.io/pypi/dm/pymiesimx.svg
169
+ :alt: Monthly PyPI downloads
170
+ :target: https://pypistats.org/packages/pymiesimx
171
+
172
+ .. |mps-demo| image:: https://img.shields.io/badge/Launch-PyMieSimX-2672d6.svg
173
+ :alt: Launch PyMieSimX
174
+ :target: https://pymiesim.onrender.com/
175
+
176
+ .. |mps-docs| image:: https://github.com/MartinPdeS/PyMieSimX/actions/workflows/deploy_documentation.yml/badge.svg
177
+ :alt: Documentation
178
+ :target: https://martinpdes.github.io/PyMieSimX/
179
+
180
+ .. |mps-ci| image:: https://github.com/MartinPdeS/PyMieSimX/actions/workflows/tests.yml/badge.svg
181
+ :alt: Tests
182
+ :target: https://github.com/MartinPdeS/PyMieSimX/actions/workflows/tests.yml
183
+
184
+ .. |mps-coverage| image:: https://raw.githubusercontent.com/MartinPdeS/PyMieSimX/python-coverage-comment-action-data/badge.svg
185
+ :alt: Test coverage
186
+ :target: https://htmlpreview.github.io/?https://github.com/MartinPdeS/PyMieSimX/blob/python-coverage-comment-action-data/htmlcov/index.html
187
+
188
+ .. |mps-conda| image:: https://anaconda.org/martinpdes/pymiesimx/badges/version.svg
189
+ :alt: Anaconda version
190
+ :target: https://anaconda.org/martinpdes/pymiesimx
191
+
192
+ .. |mps-conda-downloads| image:: https://anaconda.org/martinpdes/pymiesimx/badges/downloads.svg
193
+ :alt: Anaconda downloads
194
+ :target: https://anaconda.org/martinpdes/pymiesimx
195
+
196
+ .. |mps-conda-release| image:: https://anaconda.org/martinpdes/pymiesimx/badges/latest_release_relative_date.svg
197
+ :alt: Latest Anaconda release
198
+ :target: https://anaconda.org/martinpdes/pymiesimx
@@ -1,4 +1,4 @@
1
1
  """Release version maintained by martinpdes-maintenance."""
2
2
 
3
- __version__ = version = "0.4.8"
3
+ __version__ = version = "0.5.0"
4
4
  __version_tuple__ = version_tuple = tuple(int(part) for part in version.split("."))
@@ -0,0 +1,242 @@
1
+ """Token-gated administration dashboard for server-side usage counters."""
2
+
3
+ import hmac
4
+ import os
5
+ from collections import deque
6
+ from threading import Lock
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+ from dash import dcc, html
11
+ from flask import Response, has_request_context, redirect, request
12
+ from itsdangerous import BadData, URLSafeTimedSerializer
13
+
14
+ from PyMieSimX.gui import usage_metrics
15
+ from PyMieSimX.gui.components import Card
16
+ from PyMieSimX.gui.visit_location import request_location
17
+
18
+
19
+ ADMIN_TOKEN_ENV_VAR = "PYMIESIMX_ADMIN_TOKEN"
20
+ ADMIN_COOKIE = "pymiesimx-admin"
21
+ ADMIN_SESSION_SECONDS = 30 * 60
22
+ REFRESH_INTERVAL_MILLISECONDS = 30_000
23
+
24
+
25
+ _PUBLIC_PAGES = frozenset({
26
+ "/", "/experiment", "/single", "/population", "/examples", "/documentation", "/settings",
27
+ })
28
+ _recent_visits: deque[tuple[str, str, str]] = deque(maxlen=200)
29
+ _recent_visits_lock = Lock()
30
+
31
+
32
+ def record_page_visit(*, route: str) -> None:
33
+ """Keep a bounded history of public page visits for this process."""
34
+ if route in _PUBLIC_PAGES:
35
+ visited_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
36
+ location = request_location()
37
+ with _recent_visits_lock:
38
+ _recent_visits.appendleft((visited_at, route, location))
39
+ usage_metrics.save_page_visit(route=route, location=location)
40
+
41
+
42
+ def build_recent_visits() -> html.Div:
43
+ """Render the latest public page visits without collecting visitor identifiers."""
44
+ shared_visits = usage_metrics.load_page_visits()
45
+ with _recent_visits_lock:
46
+ visits = tuple(_recent_visits if shared_visits is None else shared_visits)
47
+ if not visits:
48
+ return html.Div("No public page visits recorded.")
49
+ return html.Div(
50
+ html.Table([
51
+ html.Thead(html.Tr([html.Th("Visited at"), html.Th("Page"), html.Th("Location")])),
52
+ html.Tbody([
53
+ html.Tr([
54
+ html.Td(visited_at),
55
+ html.Td(route),
56
+ html.Td(location or "Unavailable"),
57
+ ])
58
+ for visited_at, route, location in visits
59
+ ]),
60
+ ], className="admin-activity-table"),
61
+ className="admin-activity-scroll",
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class AdminDashboardData:
67
+ """Snapshot displayed by the administration dashboard."""
68
+
69
+ metrics: usage_metrics.UsageMetrics = field(default_factory=usage_metrics.UsageMetrics)
70
+ generated_at: str = ""
71
+
72
+
73
+ def is_admin_access_granted(provided_token: Any) -> bool:
74
+ """Return whether the provided token exactly matches server configuration."""
75
+ configured_token = os.getenv(ADMIN_TOKEN_ENV_VAR, "").strip()
76
+ candidate_token = str(provided_token or "").strip()
77
+ return bool(configured_token and candidate_token and hmac.compare_digest(configured_token.encode(), candidate_token.encode()))
78
+
79
+
80
+ def _admin_serializer(*, token: str) -> URLSafeTimedSerializer:
81
+ """Build the signer used by all workers for administrator sessions."""
82
+ return URLSafeTimedSerializer(token, salt="pymiesimx-admin-session")
83
+
84
+
85
+ def has_admin_session() -> bool:
86
+ """Verify the signed administrator cookie and its expiry on every request."""
87
+ token = os.getenv(ADMIN_TOKEN_ENV_VAR, "").strip()
88
+ if not token or not has_request_context():
89
+ return False
90
+ cookie = request.cookies.get(ADMIN_COOKIE)
91
+ if not cookie:
92
+ return False
93
+ try:
94
+ session_value: object = _admin_serializer(token=token).loads(cookie, max_age=ADMIN_SESSION_SECONDS)
95
+ return session_value == "admin"
96
+ except BadData:
97
+ return False
98
+
99
+
100
+ def admin_login() -> Response:
101
+ """Exchange a submitted administrator credential for a short-lived cookie."""
102
+ token = os.getenv(ADMIN_TOKEN_ENV_VAR, "").strip()
103
+ error = ""
104
+ status = 200
105
+ if not token:
106
+ error = "Administrator access is unavailable on this server."
107
+ status = 404
108
+ elif request.method == "POST":
109
+ if is_admin_access_granted(request.form.get("token", "")):
110
+ response = redirect("/admin", code=303)
111
+ response.set_cookie(
112
+ ADMIN_COOKIE,
113
+ _admin_serializer(token=token).dumps("admin"),
114
+ max_age=ADMIN_SESSION_SECONDS,
115
+ secure=os.getenv("RENDER") == "true" or request.is_secure,
116
+ httponly=True,
117
+ samesite="Strict",
118
+ )
119
+ response.headers["Cache-Control"] = "no-store"
120
+ return response
121
+ error = "The administrator token was incorrect."
122
+ status = 403
123
+
124
+ form = ""
125
+ if token:
126
+ form = """
127
+ <form method="post" action="/admin/login">
128
+ <label for="token">Administrator token</label>
129
+ <input id="token" name="token" type="password" autocomplete="current-password" required>
130
+ <button type="submit">Sign in</button>
131
+ </form>"""
132
+ return Response(
133
+ f"""<!doctype html>
134
+ <html lang="en"><head><meta charset="utf-8">
135
+ <meta name="viewport" content="width=device-width, initial-scale=1">
136
+ <link rel="stylesheet" href="/assets/admin-login.css">
137
+ <title>Administrator sign-in · PyMieSimX</title></head>
138
+ <body class="pymiesimx-admin-login"><main><h1>Administrator sign-in</h1>
139
+ <p role="status">{error}</p>{form}
140
+ <a href="/">Return to PyMieSimX</a></main></body></html>""",
141
+ status=status,
142
+ mimetype="text/html",
143
+ headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"},
144
+ )
145
+
146
+
147
+ def collect_admin_dashboard_data() -> AdminDashboardData:
148
+ """Load the current server-side usage counters."""
149
+ return AdminDashboardData(
150
+ metrics=usage_metrics.load_usage_metrics(),
151
+ generated_at=f"{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC",
152
+ )
153
+
154
+
155
+ def metric_text(value: object) -> str:
156
+ """Format a metric for display, including unavailable local values."""
157
+ if isinstance(value, float) and value != value:
158
+ return "NaN"
159
+ return str(value)
160
+
161
+
162
+ def dashboard_values(data: AdminDashboardData) -> tuple[str, str, str, str]:
163
+ """Return callback-ready metric values and update timestamp."""
164
+ metrics = data.metrics
165
+ return (
166
+ metric_text(metrics.home_page_visit_count),
167
+ metric_text(metrics.experiment_run_count),
168
+ metric_text(metrics.single_run_count),
169
+ f"Last updated: {data.generated_at}",
170
+ )
171
+
172
+
173
+ def build_admin_page(token: str | None = None) -> html.Div:
174
+ """Build the hidden dashboard or an intentionally generic denial page."""
175
+ if not has_admin_session() and not is_admin_access_granted(token):
176
+ return html.Div(
177
+ html.Section(
178
+ className=Card.classes(color="blue", extra="admin-access-card"),
179
+ children=[
180
+ html.H2("Page not available"),
181
+ html.P("The requested page is not available on this server."),
182
+ ],
183
+ ),
184
+ className="page-content-stack admin-page",
185
+ )
186
+
187
+ values = dashboard_values(collect_admin_dashboard_data())
188
+ tiles = (
189
+ ("admin-home-page-visits", values[0], "Home page visits"),
190
+ ("admin-experiment-runs", values[1], "Parameter sweeps"),
191
+ ("admin-single-runs", values[2], "Particle explorations"),
192
+ )
193
+ return html.Div(
194
+ className="page-content-stack admin-page",
195
+ children=[
196
+ dcc.Interval(id="admin-refresh-interval", interval=REFRESH_INTERVAL_MILLISECONDS, n_intervals=0),
197
+ html.Section(
198
+ className="admin-header",
199
+ children=[
200
+ html.H1("Administration"),
201
+ html.P("Server-side PyMieSimX usage metrics.", className="admin-description"),
202
+ html.Div(
203
+ [
204
+ html.Span(values[3], id="admin-last-updated"),
205
+ html.Button("Refresh", id="admin-refresh-button", n_clicks=0, className="admin-refresh"),
206
+ ],
207
+ className="admin-toolbar",
208
+ ),
209
+ ],
210
+ ),
211
+ html.Div(
212
+ [
213
+ html.Section(
214
+ className="admin-metric-card",
215
+ children=[
216
+ html.Div(value, id=value_id, className="admin-metric-value"),
217
+ html.Div(label, className="admin-metric-label"),
218
+ ],
219
+ )
220
+ for value_id, value, label in tiles
221
+ ],
222
+ className="admin-metric-grid",
223
+ ),
224
+ html.Section([
225
+ html.Header([
226
+ html.H2("Recent activity"),
227
+ html.P("Latest 200 public page visits. Without PostgreSQL, activity is limited to the current server process."),
228
+ ]),
229
+ html.Div(build_recent_visits(), id="admin-recent-visits"),
230
+ ], className="admin-activity-card"),
231
+ ],
232
+ )
233
+
234
+
235
+ __all__ = [
236
+ "ADMIN_TOKEN_ENV_VAR",
237
+ "AdminDashboardData",
238
+ "build_admin_page",
239
+ "collect_admin_dashboard_data",
240
+ "dashboard_values",
241
+ "is_admin_access_granted",
242
+ ]
@@ -0,0 +1,66 @@
1
+ .page-content-stack.admin-page {
2
+ width: 100%;
3
+ min-width: 0;
4
+ grid-template-columns: minmax(0, 1fr);
5
+ gap: 1.5rem;
6
+ }
7
+
8
+ .admin-header h1 { margin: 0; font-size: 1.75rem; }
9
+ .admin-description { margin: .4rem 0 1rem; color: var(--muted); }
10
+ .admin-toolbar {
11
+ display: flex;
12
+ flex-wrap: wrap;
13
+ align-items: center;
14
+ justify-content: space-between;
15
+ gap: .75rem;
16
+ color: var(--muted);
17
+ font-size: .88rem;
18
+ }
19
+
20
+ .admin-refresh {
21
+ padding: .35rem .75rem;
22
+ border: 1px solid currentColor;
23
+ border-radius: .4rem;
24
+ background: transparent;
25
+ color: var(--accent);
26
+ font: inherit;
27
+ cursor: pointer;
28
+ }
29
+ .admin-refresh:hover { background: var(--accent-soft); }
30
+
31
+ .admin-metric-grid {
32
+ display: grid;
33
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
34
+ gap: 1rem;
35
+ }
36
+ .admin-metric-card {
37
+ padding: 18px;
38
+ border: 1px solid rgba(13, 110, 253, .16);
39
+ border-radius: 12px;
40
+ background: rgba(13, 110, 253, .04);
41
+ }
42
+ .admin-metric-value { font-size: 2rem; font-weight: 800; line-height: 1; }
43
+ .admin-metric-label { margin-top: 6px; font-size: .92rem; color: var(--muted); }
44
+ .admin-access-card { max-width: 540px; margin: 3rem auto; padding: 1.5rem; }
45
+
46
+ .admin-activity-card {
47
+ min-width: 0;
48
+ border: 1px solid var(--line);
49
+ border-radius: .75rem;
50
+ background: var(--panel);
51
+ }
52
+ .admin-activity-card > header {
53
+ padding: .85rem 1rem;
54
+ border-bottom: 1px solid var(--line);
55
+ }
56
+ .admin-activity-card h2 { margin: 0; font-size: 1.05rem; }
57
+ .admin-activity-card p { margin: .3rem 0 0; font-size: .9rem; color: var(--muted); }
58
+ #admin-recent-visits { padding: 1rem; }
59
+ .admin-activity-scroll { max-height: 32rem; overflow: auto; }
60
+ .admin-activity-table { width: 100%; border-collapse: collapse; font-size: .9rem; }
61
+ .admin-activity-table :is(th, td) {
62
+ padding: .55rem .7rem;
63
+ text-align: left;
64
+ vertical-align: top;
65
+ border-bottom: 1px solid var(--line);
66
+ }
@@ -0,0 +1,32 @@
1
+ .pymiesimx-admin-login {
2
+ color: #142537;
3
+ background: #f2f6fa;
4
+ font: 1rem system-ui, sans-serif;
5
+ }
6
+
7
+ .pymiesimx-admin-login main {
8
+ max-width: 27rem;
9
+ margin: 10vh auto;
10
+ padding: 1.5rem;
11
+ background: white;
12
+ border: 1px solid #d9e2e8;
13
+ border-radius: .8rem;
14
+ }
15
+
16
+ .pymiesimx-admin-login form {
17
+ display: grid;
18
+ gap: .55rem;
19
+ margin: 1rem 0;
20
+ }
21
+
22
+ .pymiesimx-admin-login :is(input, button) {
23
+ font: inherit;
24
+ padding: .5rem;
25
+ }
26
+
27
+ .pymiesimx-admin-login button {
28
+ color: #fff;
29
+ background: #225bb1;
30
+ border: 1px solid #225bb1;
31
+ border-radius: .4rem;
32
+ }
@@ -0,0 +1,11 @@
1
+ <?xml version='1.0' encoding='utf-8'?>
2
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70.5 87.3" width="70.5" height="87.3"><style type="text/css">
3
+ .st0{fill:#E6000F;}
4
+ .st1{fill:#F07814;}
5
+ .st2{fill:#003741;}
6
+ </style>
7
+ <g><path class="st0" d="M18.8,13.4v30.7c0,11.8,2.1,17.2,5.9,20.4c2.2,1.8,5,3,8.3,4.2V41.3C32.9,29.9,27.3,19.8,18.8,13.4" />
8
+ <path class="st0" d="M51.7,13.4v30.7c0,11.8-2.1,17.2-5.9,20.4c-2.2,1.8-5,3-8.3,4.2V41.3C37.6,29.9,43.1,19.8,51.7,13.4" />
9
+ <path class="st1" d="M35.2,87.3c19.4,0,35.3-15.5,35.3-35.8l0-44.9c-5.1,0.3-9.9,1.7-14.2,4v37c0,24.6-17.8,25.5-21,25.5 c-3.3,0-21-0.9-21-25.5v-37C9.9,8.3,5.1,6.9,0,6.6l0,44.9C0,71.8,15.8,87.3,35.2,87.3" />
10
+ <path class="st2" d="M35.2,24.5c2.5-5.1,6.1-9.5,10.4-13C43,6.9,39.5,3,35.2,0C31,3,27.4,6.9,24.9,11.4 C29.2,15,32.7,19.4,35.2,24.5" />
11
+ </g></svg>