JoeTach Claude Opus 4.7 commited on
Commit
5cc4e7f
·
1 Parent(s): d02aecd

Fix CI on 3.11+3.12 and harden Streamlit against any-rerun blank

Browse files

CI was failing for two unrelated reasons that the new verbose pytest
log finally surfaced:

* **Python 3.12 — TypeError in KelvinVoigtModel.diagnostics().**
``@dataclass(slots=True)`` replaces the original class object with a
freshly constructed slotted one. The ``__class__`` cell that zero-arg
``super()`` captures at compile time still points to the pre-
replacement class, but ``self`` is an instance of the post-replacement
class --- so the runtime check ``isinstance(self, __class__)`` raises
``TypeError: super(type, obj): obj must be an instance or subtype
of type``. Replaced with an explicit ``CableModel.diagnostics(self,
...)`` call; this is correct here because ``CableModel`` is the
single base class (no diamond inheritance).

* **Python 3.11 — SyntaxError in cdpr/reports/bundle.py:216.** An
f-string slot contained ``r.scenario_name.replace('_', r'\_')``.
PEP 701 lifted the "no backslash in f-string expression" rule only
in 3.12. Hoisted the ``.replace()`` calls into local variables so
the f-string slots stay backslash-free.

Streamlit-side: the user reported the page going blank on *every*
rerun (Apply parameters, CSV upload, etc.). Root cause was widgets
that carry both ``value=`` and ``key=``: when ``st.session_state[key]``
already holds a value from a prior run, Streamlit emits a warning per
widget, and a deep enough warning chain inflates the WebSocket payload
past the free worker's limit, dropping the connection.

Fix: pre-populate every default through ``st.session_state.setdefault``
*before* any widget exists, then pass only ``key=`` to the widgets
themselves. Side benefits:
- dropped the ``st.form`` wrapper that the previous fix used (it
did not solve the blank-page symptom and made debugging harder);
- added a visible build banner (BUILD_ID) so the user can tell
instantly whether Cloud is serving the latest commit;
- added a "Reset session" button that wipes session_state;
- wrapped streamlit_app.py's gui import in try/except so a module-
load failure shows the traceback in the page rather than blanking;
- added a Diagnostics expander showing Streamlit + matplotlib +
Python + session_state info for live debugging;
- bumped a cache-bust marker in requirements.txt to force Streamlit
Cloud to discard its cached worker venv.

Local subset (mirrors CI ignores): 177 passed in ~49 s.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

requirements.txt CHANGED
@@ -6,6 +6,10 @@
6
  # pip install -e ".[dev,viz,data,api,gui]"
7
  #
8
  # What's in here = what the deployed Streamlit research console needs.
 
 
 
 
9
 
10
  streamlit>=1.32
11
 
 
6
  # pip install -e ".[dev,viz,data,api,gui]"
7
  #
8
  # What's in here = what the deployed Streamlit research console needs.
9
+ #
10
+ # Cache-bust marker: bump this when forcing Streamlit Cloud to discard a
11
+ # cached worker venv after a behavioural change in cdpr.interface.gui.
12
+ # rebuild: 2026-05-28-c
13
 
14
  streamlit>=1.32
15
 
src/cdpr/cables/kelvin_voigt.py CHANGED
@@ -132,7 +132,19 @@ class KelvinVoigtModel(CableModel):
132
  state: "PlatformState",
133
  rest_lengths: NDArray[np.float64],
134
  ) -> dict[str, Any]:
135
- base = super().diagnostics(robot, state, rest_lengths)
 
 
 
 
 
 
 
 
 
 
 
 
136
  dL_dt = self._length_rates(robot, state)
137
  base.update({
138
  "max_abs_Ldot": float(np.max(np.abs(dL_dt))),
 
132
  state: "PlatformState",
133
  rest_lengths: NDArray[np.float64],
134
  ) -> dict[str, Any]:
135
+ # NOTE: do not use ``super().diagnostics(...)`` here. The class
136
+ # carries ``@dataclass(slots=True)``, and Python's dataclass
137
+ # mechanism replaces the original class object with a freshly
138
+ # constructed slotted one. The ``__class__`` cell that zero-arg
139
+ # ``super()`` captures at compile time still refers to the
140
+ # *pre-replacement* class, but ``self`` is an instance of the
141
+ # *post-replacement* class --- so the runtime check
142
+ # ``isinstance(self, __class__)`` fails and raises
143
+ # ``TypeError: super(type, obj): obj must be an instance or
144
+ # subtype of type``. Calling the parent method by name sidesteps
145
+ # the issue entirely and is correct here because ``CableModel``
146
+ # is the single base class (no diamond inheritance).
147
+ base = CableModel.diagnostics(self, robot, state, rest_lengths)
148
  dL_dt = self._length_rates(robot, state)
149
  base.update({
150
  "max_abs_Ldot": float(np.max(np.abs(dL_dt))),
src/cdpr/interface/gui.py CHANGED
@@ -1,70 +1,72 @@
1
- r"""Streamlit research console.
2
 
3
  Launch with::
4
 
5
  pip install 'cdpr[gui,viz]'
6
  streamlit run streamlit_app.py
7
 
8
- Free-tier-aware design
9
- ----------------------
10
-
11
- Streamlit Community Cloud runs each app in a ~1 GB sandbox. The previous
12
- revision rendered every plot tab on every script rerun --- six
13
- matplotlib figures including a 3D scene --- which OOM-killed the worker
14
- right after the simulate() call finished, producing a blank page with
15
- no Python-level traceback.
16
-
17
- Two changes prevent that:
18
-
19
- 1. **Sidebar lives inside an :func:`st.form`.** Streamlit only reruns
20
- the script when the user explicitly clicks *Apply parameters* (the
21
- form's submit button) or *Run simulation*. Editing a slider mid-
22
- form no longer triggers a rerun.
23
-
24
- 2. **Only the active result tab renders a figure.** Streamlit's
25
- :func:`st.tabs` runs the body of *every* tab on every rerun, but we
26
- gate each tab's plot behind a per-tab "Render" button + a session-
27
- state cache. The 3D scene tab in particular is hidden behind an
28
- explicit opt-in because it is the heaviest figure in the framework.
29
-
30
- The console also forces ``MPLBACKEND=Agg`` upstream in
31
- ``streamlit_app.py`` (must be set before any matplotlib import).
32
-
33
- Every exception inside :func:`render` and around each plot is caught
34
- and surfaced via :func:`st.exception`; previous versions silently
35
- swallowed errors and showed a blank page.
 
 
 
36
  """
37
 
38
  from __future__ import annotations
39
 
 
 
 
40
  import os
 
41
  import traceback
42
 
43
  try:
44
  import streamlit as st
45
- except ImportError as exc:
46
  raise ImportError(
47
  "The Streamlit console needs Streamlit. Install with: pip install 'cdpr[gui]'"
48
  ) from exc
49
 
50
- # matplotlib backend must be selected before any plotting import. The
51
- # top-level streamlit_app.py sets MPLBACKEND=Agg at process start; here
52
- # we also call matplotlib.use() defensively in case the GUI is invoked
53
- # through a different entry-point.
54
- import matplotlib # noqa: E402
55
  matplotlib.use("Agg", force=True)
56
 
57
- import io # noqa: E402
58
- import sys # noqa: E402
59
 
60
- import numpy as np # noqa: E402
61
- import pandas as pd # noqa: E402
62
- from scipy.spatial.transform import Rotation # noqa: E402
63
 
64
- from cdpr.core.frames import Pose # noqa: E402
65
- from cdpr.dynamics.rigid_body import PlatformState # noqa: E402
66
- from cdpr.dynamics.simulator import simulate # noqa: E402
67
- from cdpr.interface.specs import ( # noqa: E402
68
  SimulationRequest,
69
  TrajectorySpec,
70
  build_robot,
@@ -72,150 +74,218 @@ from cdpr.interface.specs import ( # noqa: E402
72
  )
73
 
74
 
75
- # Frugal mode (free Streamlit Cloud tier) trims the default workload.
76
- FRUGAL = bool(int(os.environ.get("CDPR_GUI_FRUGAL", "0")))
 
 
 
 
 
 
 
77
 
78
 
79
  def _log(msg: str) -> None:
80
- """Write to stderr so it appears in the Streamlit Cloud manage-app log
81
- even when the in-app UI is dead."""
82
- print(f"[cdpr-gui] {msg}", file=sys.stderr, flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
 
85
  # ---------------------------------------------------------------------------
86
- # Top-level entry
87
  # ---------------------------------------------------------------------------
88
 
89
  def render() -> None:
90
- if not st.session_state.get("_page_config_set"):
91
- st.set_page_config(page_title="CDPR research console", layout="wide")
92
- st.session_state["_page_config_set"] = True
93
 
 
 
94
  try:
95
- st.title("CDPR research console")
96
- st.caption(
97
- "Configure parameters in the sidebar form, click **Apply parameters**, "
98
- "then click **Run simulation**. Plots render on demand to keep memory low."
 
 
 
 
 
 
99
  )
 
 
 
 
 
100
 
101
- request = _request_form()
102
  _action_bar(request)
103
  _results_panel()
104
  _upload_panel()
 
 
 
105
 
106
  except Exception as exc:
107
  _log(f"render() crashed: {type(exc).__name__}: {exc}")
108
- st.error(f"Unhandled exception: {type(exc).__name__}: {exc}")
109
  st.exception(exc)
110
- st.code(traceback.format_exc())
111
 
112
 
113
  # ---------------------------------------------------------------------------
114
- # Sidebar form
 
 
115
  # ---------------------------------------------------------------------------
116
 
117
- def _request_form() -> SimulationRequest:
118
- """All parameter widgets live inside a single form so Streamlit
119
- only re-runs the script on Apply."""
120
- default_duration = 0.5 if FRUGAL else 1.5
121
- default_dt = 5e-3 if FRUGAL else 2e-3
122
-
123
  with st.sidebar:
124
- with st.form("params_form", clear_on_submit=False):
125
- st.header("Experiment")
126
- robot_name = st.selectbox(
127
- "Robot",
128
- ["ipanema_class", "cogiro_class", "point_mass_3d", "planar_translational"],
129
- index=0,
130
- key="robot_name",
131
- )
132
- payload = st.number_input(
133
- "Payload mass [kg]", min_value=0.0, value=0.0, step=0.5, key="payload",
134
- )
 
 
 
135
 
136
- st.divider()
137
- st.header("Trajectory")
138
- kind = st.selectbox(
139
- "Kind", ["hold", "line", "circle", "lissajous"], index=2, key="kind",
140
- )
141
- duration = st.number_input(
142
- "Duration [s]", min_value=0.05, max_value=5.0,
143
- value=default_duration, step=0.05, key="duration",
144
- )
145
- dt = st.number_input(
146
- "Time step dt [s]", min_value=1e-4, max_value=5e-2,
147
- value=default_dt, step=1e-3, format="%.4f", key="dt",
148
- )
149
 
150
- st.subheader("Line parameters")
151
- line_start = st.text_input("start (x,y,z) [m]", "0,0,0", key="line_start")
152
- line_end = st.text_input("end (x,y,z) [m]", "0.3,0,0", key="line_end")
153
 
154
- st.subheader("Circle parameters")
155
- circle_radius = st.slider(
156
- "radius [m]", 0.05, 1.0, 0.3, step=0.05, key="circle_radius",
157
- )
158
- circle_axis = st.selectbox(
159
- "axis", ["z", "y", "x"], index=0, key="circle_axis",
160
- )
 
161
 
162
- st.subheader("Lissajous amplitudes [m]")
163
- liss_ax = st.slider("Ax", 0.0, 1.0, 0.3, step=0.05, key="liss_ax")
164
- liss_ay = st.slider("Ay", 0.0, 1.0, 0.2, step=0.05, key="liss_ay")
165
- liss_az = st.slider("Az", 0.0, 1.0, 0.0, step=0.05, key="liss_az")
166
- st.subheader("Lissajous frequencies [-]")
167
- liss_fx = st.slider("fx", 1.0, 5.0, 1.0, step=0.5, key="liss_fx")
168
- liss_fy = st.slider("fy", 1.0, 5.0, 2.0, step=0.5, key="liss_fy")
169
- liss_fz = st.slider("fz", 0.0, 5.0, 0.0, step=0.5, key="liss_fz")
170
-
171
- st.divider()
172
- st.header("Solver")
173
- integrator = st.radio(
174
- "Integrator", ["rk4", "semi_implicit"], horizontal=True, key="integrator",
175
- )
176
- objective = st.radio(
177
- "Tension objective", ["centered", "min_norm", "preferred"],
178
- horizontal=True, key="objective",
179
- )
180
 
181
- applied = st.form_submit_button(
182
- "Apply parameters", type="secondary", use_container_width=True,
183
- )
 
 
184
 
 
 
185
  if kind == "line":
186
  params: dict = {
187
- "start": _parse_xyz(line_start, default=[0.0, 0.0, 0.0]),
188
- "end": _parse_xyz(line_end, default=[0.3, 0.0, 0.0]),
189
  }
190
  elif kind == "circle":
191
- axis_vec = {"x": [1, 0, 0], "y": [0, 1, 0], "z": [0, 0, 1]}[circle_axis]
192
  params = {
193
- "center": [0.0, 0.0, 0.0],
194
- "radius": float(circle_radius),
195
- "axis": axis_vec,
196
- "angle_span": 2 * np.pi,
197
  }
198
  elif kind == "lissajous":
199
  params = {
200
- "center": [0.0, 0.0, 0.0],
201
- "amplitudes": [float(liss_ax), float(liss_ay), float(liss_az)],
202
- "frequencies": [float(liss_fx), float(liss_fy), float(liss_fz)],
203
- "phases": [0.0, np.pi / 2, 0.0],
204
  }
205
  else: # hold
206
  params = {}
207
 
208
- if applied:
209
- st.toast("Parameters applied.")
210
-
211
  return SimulationRequest(
212
- robot=robot_name, # type: ignore[arg-type]
213
- trajectory=TrajectorySpec(kind=kind, duration=duration, params=params), # type: ignore[arg-type]
214
- duration=duration,
215
- dt=dt,
216
- integrator=integrator, # type: ignore[arg-type]
217
- tension_objective=objective, # type: ignore[arg-type]
218
- payload_mass=payload,
 
 
219
  )
220
 
221
 
@@ -225,12 +295,12 @@ def _parse_xyz(text: str, *, default: list[float]) -> list[float]:
225
  if len(parts) != 3:
226
  return list(default)
227
  return [float(p) for p in parts]
228
- except (ValueError, TypeError):
229
  return list(default)
230
 
231
 
232
  # ---------------------------------------------------------------------------
233
- # Action bar
234
  # ---------------------------------------------------------------------------
235
 
236
  def _action_bar(request: SimulationRequest) -> None:
@@ -238,42 +308,41 @@ def _action_bar(request: SimulationRequest) -> None:
238
  if cols[0].button("Run simulation", type="primary", key="btn_run"):
239
  try:
240
  _log(
241
- f"Run simulation: robot={request.robot} kind={request.trajectory.kind} "
242
  f"duration={request.duration} dt={request.dt}"
243
  )
244
- with st.spinner("Integrating..."):
245
  robot = build_robot(request.robot, payload_mass=request.payload_mass)
246
  ref = build_trajectory(request.trajectory)
247
- initial_pose = Pose(position=np.zeros(3), rotation=Rotation.identity())
 
248
  result = simulate(
249
  robot=robot,
250
- state0=PlatformState.at_rest(initial_pose),
 
251
  duration=request.duration,
252
  dt=request.dt,
253
- reference_pose=ref,
254
- integrator=request.integrator,
255
  tension_objective=request.tension_objective,
256
  gravity=request.gravity,
257
  )
258
- _log(f"Simulation finished: {len(result.time)} samples")
259
  st.session_state["last_result"] = result
260
  st.session_state["last_robot"] = robot
261
  st.session_state["last_reference"] = ref
262
- # Invalidate cached figures from a previous run.
263
  st.session_state.pop("_figure_cache", None)
264
  st.toast(f"Simulation finished ({len(result.time)} samples).")
265
  except Exception as exc:
266
- _log(f"Simulation crashed: {type(exc).__name__}: {exc}")
267
  st.error(f"Simulation failed: {type(exc).__name__}: {exc}")
268
  st.exception(exc)
269
  if cols[1].button("Clear cached run", key="btn_clear"):
270
- for key in ("last_result", "last_robot", "last_reference", "_figure_cache"):
271
- st.session_state.pop(key, None)
272
  st.toast("Cleared.")
273
 
274
 
275
  # ---------------------------------------------------------------------------
276
- # Results panel — lazy per-tab rendering
277
  # ---------------------------------------------------------------------------
278
 
279
  def _results_panel() -> None:
@@ -281,41 +350,29 @@ def _results_panel() -> None:
281
  robot = st.session_state.get("last_robot")
282
  reference = st.session_state.get("last_reference")
283
  if result is None or robot is None:
284
- st.info(
285
- "Configure parameters in the sidebar, click **Apply parameters**, "
286
- "then click **Run simulation**."
287
- )
288
  return
289
 
290
- # Top-line summary --- cheap, render unconditionally.
291
- summary_cols = st.columns(4)
292
- summary_cols[0].metric("samples", len(result.time))
293
- summary_cols[1].metric(
294
- "max |p|", f"{np.linalg.norm(result.positions, axis=1).max():.3f} m",
295
- )
296
- summary_cols[2].metric(
297
- "tension range",
298
- f"{result.cable_tensions.min():.0f} – {result.cable_tensions.max():.0f} N",
299
  )
300
- summary_cols[3].metric("infeasible steps", len(result.infeasible_steps))
301
 
302
- # Per-tab lazy plot rendering. Each tab has a Render button + a cached
303
- # figure in session_state, so:
304
- # - on the first run, nothing renders until the user asks for a plot;
305
- # - once rendered, the figure is reused across reruns (no recompute);
306
- # - the 3D scene tab is opt-in only because it is the heaviest.
307
  tab_labels = [
308
  "Position", "Cable tensions", "Cable lengths",
309
  "Tracking error", "Condition number", "3D scene (heavy)",
310
  ]
311
  tabs = st.tabs(tab_labels)
312
-
313
- _lazy_tab(tabs[0], "position", lambda: _plot_position(result))
314
- _lazy_tab(tabs[1], "cable_tensions", lambda: _plot_cable_tensions(result, robot))
315
- _lazy_tab(tabs[2], "cable_lengths", lambda: _plot_cable_lengths(result))
316
- _lazy_tab(tabs[3], "tracking_error", lambda: _plot_tracking_error(result, reference))
317
  _lazy_tab(tabs[4], "condition_number", lambda: _plot_condition_number(result, robot))
318
- _lazy_tab(tabs[5], "scene_3d", lambda: _plot_scene_3d(result, robot), warn_heavy=True)
319
 
320
 
321
  def _lazy_tab(tab, key: str, render_fn, *, warn_heavy: bool = False) -> None:
@@ -323,52 +380,54 @@ def _lazy_tab(tab, key: str, render_fn, *, warn_heavy: bool = False) -> None:
323
  with tab:
324
  if warn_heavy:
325
  st.caption(
326
- "The 3D scene is the heaviest figure and can OOM the free Streamlit "
327
- "Cloud worker. Click below to render."
328
  )
329
  if key in cache:
330
  st.pyplot(cache[key], clear_figure=False)
331
  if st.button(f"Re-render {key}", key=f"rerender_{key}"):
332
  cache.pop(key, None)
333
  st.rerun()
334
- else:
335
- if st.button(f"Render {key}", key=f"render_{key}", type="primary"):
336
- try:
337
- _log(f"Rendering {key}...")
338
- fig = render_fn()
339
- cache[key] = fig
340
- _log(f"Rendered {key}.")
341
- st.rerun()
342
- except Exception as exc:
343
- _log(f"Render {key} failed: {type(exc).__name__}: {exc}")
344
- st.error(f"Could not render {key}: {type(exc).__name__}: {exc}")
345
- st.exception(exc)
346
 
347
 
348
  # ---------------------------------------------------------------------------
349
- # Plot factories — imported lazily so the module load cost stays small
350
  # ---------------------------------------------------------------------------
351
 
 
 
 
 
 
 
 
 
352
  def _plot_position(result):
353
- import matplotlib.pyplot as plt
354
  from cdpr.viz import plots2d
355
- from cdpr.viz.style import apply_paper_style
356
- apply_paper_style()
357
- fig = plots2d.plot_position(result)
358
- return fig
359
 
360
 
361
  def _plot_cable_tensions(result, robot):
 
362
  from cdpr.viz import plots2d
363
- from cdpr.viz.style import apply_paper_style
364
- apply_paper_style()
365
  return plots2d.plot_cable_tensions(result, robot=robot)
366
 
367
 
368
  def _plot_cable_lengths(result):
 
369
  from cdpr.viz import plots2d
370
- from cdpr.viz.style import apply_paper_style
371
- apply_paper_style()
372
  return plots2d.plot_cable_lengths(result)
373
 
374
 
@@ -380,28 +439,24 @@ def _plot_tracking_error(result, reference):
380
  ha="center", va="center", transform=ax.transAxes)
381
  ax.set_axis_off()
382
  return fig
 
383
  from cdpr.viz import plots2d
384
- from cdpr.viz.style import apply_paper_style
385
- apply_paper_style()
386
  return plots2d.plot_tracking_error(result, reference)
387
 
388
 
389
  def _plot_condition_number(result, robot):
 
390
  from cdpr.viz import plots2d
391
- from cdpr.viz.style import apply_paper_style
392
- apply_paper_style()
393
  return plots2d.plot_condition_number(result, robot)
394
 
395
 
396
  def _plot_scene_3d(result, robot):
 
397
  from cdpr.viz.scene import SceneOptions, render_scene
398
- from cdpr.viz.style import apply_paper_style
399
- apply_paper_style()
400
  snapshot_pose = Pose(
401
  position=result.positions[-1],
402
  rotation=Rotation.from_quat(result.quaternions_xyzw[-1]),
403
  )
404
- # Keep the trajectory subsampled to control memory footprint.
405
  traj = result.positions
406
  if len(traj) > 200:
407
  traj = traj[:: max(1, len(traj) // 200)]
@@ -414,12 +469,12 @@ def _plot_scene_3d(result, robot):
414
 
415
 
416
  # ---------------------------------------------------------------------------
417
- # Upload panel
418
  # ---------------------------------------------------------------------------
419
 
420
  def _upload_panel() -> None:
421
  st.divider()
422
- st.subheader("Experiment upload")
423
  uploaded = st.file_uploader(
424
  "Drop a CSV / XLSX experimental log",
425
  type=["csv", "xlsx", "xls"],
@@ -442,5 +497,37 @@ def _upload_panel() -> None:
442
  st.exception(exc)
443
 
444
 
445
- # Streamlit executes the module body when launched via `streamlit run`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  render()
 
1
+ r"""Streamlit research console for the CDPR framework.
2
 
3
  Launch with::
4
 
5
  pip install 'cdpr[gui,viz]'
6
  streamlit run streamlit_app.py
7
 
8
+ Design notes (why the page used to go blank on every rerun)
9
+ -----------------------------------------------------------
10
+
11
+ Streamlit Community Cloud runs each app in a ~1 GB sandbox. Two
12
+ distinct failure modes hit earlier revisions:
13
+
14
+ 1. **Run-simulation OOM.** The previous results panel rendered six
15
+ matplotlib figures --- including a 3D scene with the full trajectory
16
+ --- on every script rerun. The worker was killed before the WebSocket
17
+ could deliver the first frame, so the user saw a blank page with no
18
+ Python-level traceback. Fix: per-tab lazy rendering. Each plot has
19
+ a "Render" button and its figure is cached in ``st.session_state``
20
+ for the lifetime of the simulation result.
21
+
22
+ 2. **Any-rerun blank.** Widgets that carry both ``value=`` and ``key=``
23
+ trigger a warning if ``st.session_state[key]`` was already set by a
24
+ previous run with a different value (e.g. after a redeploy that
25
+ changed the default). On Cloud's free worker a deep enough warning
26
+ chain (Streamlit emits one *per* widget) inflates the WebSocket
27
+ payload past its limit and the page disconnects silently. Fix:
28
+ pre-populate every default through :func:`st.session_state.setdefault`
29
+ *before* widgets are created, and pass only ``key=`` to the widget
30
+ (no ``value=`` / ``index=``).
31
+
32
+ Everything inside :func:`render` runs under a top-level try/except.
33
+ Any uncaught exception is shown via :func:`st.exception` plus a
34
+ ``traceback`` block --- so the user always sees the failure cause
35
+ rather than a blank page.
36
+
37
+ A short ``_log()`` helper writes to stderr so the Streamlit Cloud
38
+ "manage app" log carries breadcrumbs even when the in-app UI is gone.
39
  """
40
 
41
  from __future__ import annotations
42
 
43
+ # ---- Streamlit & matplotlib are imported FIRST so backend pinning happens
44
+ # ---- before any plotting module sees matplotlib for the first time.
45
+
46
  import os
47
+ import sys
48
  import traceback
49
 
50
  try:
51
  import streamlit as st
52
+ except ImportError as exc: # pragma: no cover
53
  raise ImportError(
54
  "The Streamlit console needs Streamlit. Install with: pip install 'cdpr[gui]'"
55
  ) from exc
56
 
57
+ import matplotlib # noqa: E402
 
 
 
 
58
  matplotlib.use("Agg", force=True)
59
 
60
+ import io # noqa: E402
 
61
 
62
+ import numpy as np # noqa: E402
63
+ import pandas as pd # noqa: E402
64
+ from scipy.spatial.transform import Rotation # noqa: E402
65
 
66
+ from cdpr.core.frames import Pose # noqa: E402
67
+ from cdpr.dynamics.rigid_body import PlatformState # noqa: E402
68
+ from cdpr.dynamics.simulator import simulate # noqa: E402
69
+ from cdpr.interface.specs import ( # noqa: E402
70
  SimulationRequest,
71
  TrajectorySpec,
72
  build_robot,
 
74
  )
75
 
76
 
77
+ # Build-id banner: lets the user tell instantly whether Streamlit Cloud
78
+ # is serving the latest commit or a stale cached worker. Bump when the
79
+ # behavioural contract of this file changes.
80
+ BUILD_ID = "gui-2026-05-28-c"
81
+
82
+ # Frugal mode trims the *simulator* workload to keep the integration
83
+ # cheap on the free tier (1 GB / 1 vCPU). Plot rendering is already
84
+ # fully lazy, so this knob only affects how long simulate() runs.
85
+ FRUGAL = bool(int(os.environ.get("CDPR_GUI_FRUGAL", "1")))
86
 
87
 
88
  def _log(msg: str) -> None:
89
+ """Write to stderr so it surfaces in Streamlit Cloud's manage-app log."""
90
+ print(f"[cdpr-gui] {BUILD_ID} :: {msg}", file=sys.stderr, flush=True)
91
+
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # set_page_config must be the first Streamlit call in the process and is
95
+ # allowed to run exactly once. Use a module-level flag (not session_state)
96
+ # so it survives any session_state.clear() in the Reset button.
97
+ # ---------------------------------------------------------------------------
98
+
99
+ _PAGE_CONFIG_DONE = False
100
+
101
+
102
+ def _ensure_page_config() -> None:
103
+ global _PAGE_CONFIG_DONE
104
+ if _PAGE_CONFIG_DONE:
105
+ return
106
+ try:
107
+ st.set_page_config(
108
+ page_title="CDPR research console",
109
+ layout="wide",
110
+ initial_sidebar_state="expanded",
111
+ )
112
+ except Exception as exc: # pragma: no cover
113
+ # Streamlit raises on duplicate set_page_config; treat as benign.
114
+ _log(f"set_page_config skipped: {type(exc).__name__}: {exc}")
115
+ _PAGE_CONFIG_DONE = True
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # Default state setup --- runs once per session before any widget exists.
120
+ # ---------------------------------------------------------------------------
121
+
122
+ def _seed_defaults() -> None:
123
+ """Populate :mod:`st.session_state` with widget defaults.
124
+
125
+ We seed *before* creating any widget so we never have to pass both
126
+ ``value=`` and ``key=`` simultaneously --- the source of the
127
+ repeated 'value-and-state-may-differ' warnings that previously
128
+ inflated the rerun WebSocket payload past Cloud's limit.
129
+ """
130
+ defaults: dict[str, object] = {
131
+ "robot": "point-mass",
132
+ "payload_mass": 0.0,
133
+ "gravity": True,
134
+ "tension_min": 5.0,
135
+ "tension_max": 1500.0,
136
+ "kind": "circle",
137
+ "duration": 0.5 if FRUGAL else 1.5,
138
+ "dt": 5e-3 if FRUGAL else 2e-3,
139
+ "line_start": "0,0,0",
140
+ "line_end": "0.3,0,0",
141
+ "circle_center": "0,0,0.5",
142
+ "circle_radius": 0.2,
143
+ "circle_period": 1.5,
144
+ "lissajous_amplitude": "0.2,0.2,0.0",
145
+ "lissajous_omega": "2,3,0",
146
+ "lissajous_phase": "0,1.5708,0",
147
+ "objective": "min_norm",
148
+ }
149
+ for key, value in defaults.items():
150
+ st.session_state.setdefault(key, value)
151
 
152
 
153
  # ---------------------------------------------------------------------------
154
+ # Top-level entry --- imported & called by streamlit_app.py at script start.
155
  # ---------------------------------------------------------------------------
156
 
157
  def render() -> None:
158
+ _ensure_page_config()
159
+ _seed_defaults()
 
160
 
161
+ # Wrap *everything* below in a top-level try/except so any failure
162
+ # is reported in-app rather than blanking the page.
163
  try:
164
+ _log("render() begin")
165
+
166
+ # Visible build banner + reset escape hatch.
167
+ top = st.columns([6, 1])
168
+ top[0].title("CDPR research console")
169
+ top[0].caption(
170
+ f"Build {BUILD_ID}. Configure parameters in the sidebar, click "
171
+ "**Run simulation**, then use the **Render** button inside each "
172
+ "result tab. Plot rendering is lazy to fit the free Streamlit "
173
+ "Cloud worker."
174
  )
175
+ if top[1].button("Reset session", key="btn_reset"):
176
+ for k in list(st.session_state.keys()):
177
+ if k != "_page_config_done":
178
+ del st.session_state[k]
179
+ st.rerun()
180
 
181
+ request = _request_sidebar()
182
  _action_bar(request)
183
  _results_panel()
184
  _upload_panel()
185
+ _diagnostics_expander()
186
+
187
+ _log("render() end")
188
 
189
  except Exception as exc:
190
  _log(f"render() crashed: {type(exc).__name__}: {exc}")
191
+ st.error(f"Unhandled exception in console: {type(exc).__name__}: {exc}")
192
  st.exception(exc)
193
+ st.code(traceback.format_exc(), language="text")
194
 
195
 
196
  # ---------------------------------------------------------------------------
197
+ # Sidebar widgets (NO st.form --- the form added before did not fix the
198
+ # blank-page-on-rerun symptom and made debugging harder). Every widget
199
+ # has only `key=`; their initial values came from _seed_defaults().
200
  # ---------------------------------------------------------------------------
201
 
202
+ def _request_sidebar() -> SimulationRequest:
 
 
 
 
 
203
  with st.sidebar:
204
+ st.header("Experiment")
205
+ st.selectbox(
206
+ "Robot", ["point-mass", "planar", "ipanema", "cogiro"], key="robot",
207
+ )
208
+ st.number_input(
209
+ "Payload mass [kg]", min_value=0.0, step=0.1, key="payload_mass",
210
+ )
211
+ st.checkbox("Apply gravity", key="gravity")
212
+ st.number_input(
213
+ "Tension min [N]", min_value=0.0, step=1.0, key="tension_min",
214
+ )
215
+ st.number_input(
216
+ "Tension max [N]", min_value=0.0, step=10.0, key="tension_max",
217
+ )
218
 
219
+ st.header("Trajectory")
220
+ st.selectbox(
221
+ "Kind", ["hold", "line", "circle", "lissajous"], key="kind",
222
+ )
223
+ st.number_input(
224
+ "Duration [s]",
225
+ min_value=0.05, max_value=5.0, step=0.05, key="duration",
226
+ )
227
+ st.number_input(
228
+ "Time step dt [s]",
229
+ min_value=1e-4, max_value=5e-2, step=1e-3,
230
+ format="%.4f", key="dt",
231
+ )
232
 
233
+ st.subheader("Line")
234
+ st.text_input("start (x,y,z) [m]", key="line_start")
235
+ st.text_input("end (x,y,z) [m]", key="line_end")
236
 
237
+ st.subheader("Circle")
238
+ st.text_input("center (x,y,z) [m]", key="circle_center")
239
+ st.number_input(
240
+ "radius [m]", min_value=0.0, step=0.05, key="circle_radius",
241
+ )
242
+ st.number_input(
243
+ "period [s]", min_value=0.1, step=0.1, key="circle_period",
244
+ )
245
 
246
+ st.subheader("Lissajous")
247
+ st.text_input("amplitude (x,y,z) [m]", key="lissajous_amplitude")
248
+ st.text_input("omega (x,y,z) [rad/s]", key="lissajous_omega")
249
+ st.text_input("phase (x,y,z) [rad]", key="lissajous_phase")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
 
251
+ st.header("Tension distribution")
252
+ st.radio(
253
+ "Objective", ["min_norm", "centered", "preferred"],
254
+ horizontal=True, key="objective",
255
+ )
256
 
257
+ # Build params dict from current state.
258
+ kind = st.session_state["kind"]
259
  if kind == "line":
260
  params: dict = {
261
+ "start": _parse_xyz(st.session_state["line_start"], default=[0.0, 0.0, 0.0]),
262
+ "end": _parse_xyz(st.session_state["line_end"], default=[0.3, 0.0, 0.0]),
263
  }
264
  elif kind == "circle":
 
265
  params = {
266
+ "center": _parse_xyz(st.session_state["circle_center"], default=[0.0, 0.0, 0.5]),
267
+ "radius": float(st.session_state["circle_radius"]),
268
+ "period": float(st.session_state["circle_period"]),
 
269
  }
270
  elif kind == "lissajous":
271
  params = {
272
+ "amplitude": _parse_xyz(st.session_state["lissajous_amplitude"], default=[0.2, 0.2, 0.0]),
273
+ "omega": _parse_xyz(st.session_state["lissajous_omega"], default=[2.0, 3.0, 0.0]),
274
+ "phase": _parse_xyz(st.session_state["lissajous_phase"], default=[0.0, np.pi / 2, 0.0]),
 
275
  }
276
  else: # hold
277
  params = {}
278
 
 
 
 
279
  return SimulationRequest(
280
+ robot=st.session_state["robot"],
281
+ payload_mass=float(st.session_state["payload_mass"]),
282
+ gravity=bool(st.session_state["gravity"]),
283
+ tension_min=float(st.session_state["tension_min"]),
284
+ tension_max=float(st.session_state["tension_max"]),
285
+ tension_objective=st.session_state["objective"],
286
+ duration=float(st.session_state["duration"]),
287
+ dt=float(st.session_state["dt"]),
288
+ trajectory=TrajectorySpec(kind=kind, params=params),
289
  )
290
 
291
 
 
295
  if len(parts) != 3:
296
  return list(default)
297
  return [float(p) for p in parts]
298
+ except (TypeError, ValueError):
299
  return list(default)
300
 
301
 
302
  # ---------------------------------------------------------------------------
303
+ # Action bar --- Run simulation + Clear
304
  # ---------------------------------------------------------------------------
305
 
306
  def _action_bar(request: SimulationRequest) -> None:
 
308
  if cols[0].button("Run simulation", type="primary", key="btn_run"):
309
  try:
310
  _log(
311
+ f"Run: robot={request.robot} kind={request.trajectory.kind} "
312
  f"duration={request.duration} dt={request.dt}"
313
  )
314
+ with st.spinner("Integrating…"):
315
  robot = build_robot(request.robot, payload_mass=request.payload_mass)
316
  ref = build_trajectory(request.trajectory)
317
+ p0 = ref(0.0).position
318
+ state0 = PlatformState.from_pose(Pose.from_translation(p0))
319
  result = simulate(
320
  robot=robot,
321
+ state0=state0,
322
+ reference=ref,
323
  duration=request.duration,
324
  dt=request.dt,
 
 
325
  tension_objective=request.tension_objective,
326
  gravity=request.gravity,
327
  )
328
+ _log(f"Sim ok: {len(result.time)} samples")
329
  st.session_state["last_result"] = result
330
  st.session_state["last_robot"] = robot
331
  st.session_state["last_reference"] = ref
 
332
  st.session_state.pop("_figure_cache", None)
333
  st.toast(f"Simulation finished ({len(result.time)} samples).")
334
  except Exception as exc:
335
+ _log(f"Sim crashed: {type(exc).__name__}: {exc}")
336
  st.error(f"Simulation failed: {type(exc).__name__}: {exc}")
337
  st.exception(exc)
338
  if cols[1].button("Clear cached run", key="btn_clear"):
339
+ for k in ("last_result", "last_robot", "last_reference", "_figure_cache"):
340
+ st.session_state.pop(k, None)
341
  st.toast("Cleared.")
342
 
343
 
344
  # ---------------------------------------------------------------------------
345
+ # Results panel --- lazy per-tab rendering.
346
  # ---------------------------------------------------------------------------
347
 
348
  def _results_panel() -> None:
 
350
  robot = st.session_state.get("last_robot")
351
  reference = st.session_state.get("last_reference")
352
  if result is None or robot is None:
353
+ st.info("Configure parameters in the sidebar, then click **Run simulation**.")
 
 
 
354
  return
355
 
356
+ cols = st.columns(4)
357
+ cols[0].metric("samples", len(result.time))
358
+ cols[1].metric("duration [s]", f"{float(result.time[-1]):.3f}")
359
+ cols[2].metric(
360
+ "max tension [N]",
361
+ f"{float(np.max(result.cable_tensions)):.1f}",
 
 
 
362
  )
363
+ cols[3].metric("infeasible steps", len(result.infeasible_steps))
364
 
 
 
 
 
 
365
  tab_labels = [
366
  "Position", "Cable tensions", "Cable lengths",
367
  "Tracking error", "Condition number", "3D scene (heavy)",
368
  ]
369
  tabs = st.tabs(tab_labels)
370
+ _lazy_tab(tabs[0], "position", lambda: _plot_position(result))
371
+ _lazy_tab(tabs[1], "cable_tensions", lambda: _plot_cable_tensions(result, robot))
372
+ _lazy_tab(tabs[2], "cable_lengths", lambda: _plot_cable_lengths(result))
373
+ _lazy_tab(tabs[3], "tracking_error", lambda: _plot_tracking_error(result, reference))
 
374
  _lazy_tab(tabs[4], "condition_number", lambda: _plot_condition_number(result, robot))
375
+ _lazy_tab(tabs[5], "scene_3d", lambda: _plot_scene_3d(result, robot), warn_heavy=True)
376
 
377
 
378
  def _lazy_tab(tab, key: str, render_fn, *, warn_heavy: bool = False) -> None:
 
380
  with tab:
381
  if warn_heavy:
382
  st.caption(
383
+ "The 3D scene is the heaviest figure --- click below to render."
 
384
  )
385
  if key in cache:
386
  st.pyplot(cache[key], clear_figure=False)
387
  if st.button(f"Re-render {key}", key=f"rerender_{key}"):
388
  cache.pop(key, None)
389
  st.rerun()
390
+ return
391
+ if st.button(f"Render {key}", key=f"render_{key}", type="primary"):
392
+ try:
393
+ _log(f"Render {key}…")
394
+ fig = render_fn()
395
+ cache[key] = fig
396
+ _log(f"Render {key} ok")
397
+ st.rerun()
398
+ except Exception as exc:
399
+ _log(f"Render {key} crashed: {type(exc).__name__}: {exc}")
400
+ st.error(f"Could not render {key}: {type(exc).__name__}: {exc}")
401
+ st.exception(exc)
402
 
403
 
404
  # ---------------------------------------------------------------------------
405
+ # Plot factories --- imported lazily to keep module-load cheap.
406
  # ---------------------------------------------------------------------------
407
 
408
+ def _apply_style() -> None:
409
+ try:
410
+ from cdpr.viz.style import apply_paper_style
411
+ apply_paper_style()
412
+ except Exception as exc: # pragma: no cover
413
+ _log(f"apply_paper_style skipped: {type(exc).__name__}: {exc}")
414
+
415
+
416
  def _plot_position(result):
417
+ _apply_style()
418
  from cdpr.viz import plots2d
419
+ return plots2d.plot_position(result)
 
 
 
420
 
421
 
422
  def _plot_cable_tensions(result, robot):
423
+ _apply_style()
424
  from cdpr.viz import plots2d
 
 
425
  return plots2d.plot_cable_tensions(result, robot=robot)
426
 
427
 
428
  def _plot_cable_lengths(result):
429
+ _apply_style()
430
  from cdpr.viz import plots2d
 
 
431
  return plots2d.plot_cable_lengths(result)
432
 
433
 
 
439
  ha="center", va="center", transform=ax.transAxes)
440
  ax.set_axis_off()
441
  return fig
442
+ _apply_style()
443
  from cdpr.viz import plots2d
 
 
444
  return plots2d.plot_tracking_error(result, reference)
445
 
446
 
447
  def _plot_condition_number(result, robot):
448
+ _apply_style()
449
  from cdpr.viz import plots2d
 
 
450
  return plots2d.plot_condition_number(result, robot)
451
 
452
 
453
  def _plot_scene_3d(result, robot):
454
+ _apply_style()
455
  from cdpr.viz.scene import SceneOptions, render_scene
 
 
456
  snapshot_pose = Pose(
457
  position=result.positions[-1],
458
  rotation=Rotation.from_quat(result.quaternions_xyzw[-1]),
459
  )
 
460
  traj = result.positions
461
  if len(traj) > 200:
462
  traj = traj[:: max(1, len(traj) // 200)]
 
469
 
470
 
471
  # ---------------------------------------------------------------------------
472
+ # CSV / XLSX peek
473
  # ---------------------------------------------------------------------------
474
 
475
  def _upload_panel() -> None:
476
  st.divider()
477
+ st.subheader("Experimental log")
478
  uploaded = st.file_uploader(
479
  "Drop a CSV / XLSX experimental log",
480
  type=["csv", "xlsx", "xls"],
 
497
  st.exception(exc)
498
 
499
 
500
+ # ---------------------------------------------------------------------------
501
+ # Diagnostics expander --- visible breadcrumb of what state Streamlit
502
+ # thinks it has. Helpful when the page goes blank: open the expander on
503
+ # the previous run to inspect what the worker saw.
504
+ # ---------------------------------------------------------------------------
505
+
506
+ def _diagnostics_expander() -> None:
507
+ with st.expander("Diagnostics", expanded=False):
508
+ try:
509
+ import streamlit as _st_mod
510
+ st.write({
511
+ "build_id": BUILD_ID,
512
+ "streamlit_version": getattr(_st_mod, "__version__", "?"),
513
+ "matplotlib_backend": matplotlib.get_backend(),
514
+ "frugal_mode": FRUGAL,
515
+ "python": sys.version.split()[0],
516
+ "session_state_keys": sorted(
517
+ k for k in st.session_state.keys()
518
+ if not k.startswith("_")
519
+ ),
520
+ "cached_figures": list(
521
+ (st.session_state.get("_figure_cache") or {}).keys()
522
+ ),
523
+ })
524
+ except Exception as exc: # pragma: no cover
525
+ st.warning(f"diagnostics unavailable: {exc}")
526
+
527
+
528
+ # ---------------------------------------------------------------------------
529
+ # Entry point --- importing this module under `streamlit run` immediately
530
+ # kicks off the render. Streamlit replays the script on every interaction.
531
+ # ---------------------------------------------------------------------------
532
+
533
  render()
src/cdpr/reports/bundle.py CHANGED
@@ -210,10 +210,14 @@ def _write_latex(runs: list["BenchmarkRun"], path: Path, caption: str, label: st
210
  ]
211
  for r in runs:
212
  m = r.metrics
213
- # Escape underscores for LaTeX.
 
 
 
 
214
  mode_str = m.cable_mode.replace("_", r"\_")
215
  lines.append(
216
- fr" {r.scenario_name.replace('_', r'\_')} & {r.backend} & {mode_str} & "
217
  fr"{m.tracking_error_rms:.3g} & {m.tracking_error_peak:.3g} & "
218
  fr"{m.orientation_error_rms_deg:.3g} & {m.feasibility_rate:.3g} & "
219
  fr"{m.condition_number_max:.3g} & {m.runtime_s:.3g} \\"
 
210
  ]
211
  for r in runs:
212
  m = r.metrics
213
+ # Escape underscores for LaTeX. Hoist the replace() calls into
214
+ # locals --- f-string expressions cannot contain a backslash on
215
+ # Python <3.12 (PEP 701 lifted the restriction only in 3.12).
216
+ scenario_str = r.scenario_name.replace("_", r"\_")
217
+ backend_str = r.backend.replace("_", r"\_")
218
  mode_str = m.cable_mode.replace("_", r"\_")
219
  lines.append(
220
+ fr" {scenario_str} & {backend_str} & {mode_str} & "
221
  fr"{m.tracking_error_rms:.3g} & {m.tracking_error_peak:.3g} & "
222
  fr"{m.orientation_error_rms_deg:.3g} & {m.feasibility_rate:.3g} & "
223
  fr"{m.condition_number_max:.3g} & {m.runtime_s:.3g} \\"
streamlit_app.py CHANGED
@@ -12,12 +12,17 @@ backends will either fail to import or hang on the first figure draw,
12
  which produces a blank page with no Python-level traceback. The
13
  ``Agg`` setting is forced here at the very top of the entry-point so
14
  every later import sees it.
 
 
 
 
15
  """
16
 
17
  from __future__ import annotations
18
 
19
  import os
20
  import sys
 
21
  from pathlib import Path
22
 
23
  # 1) Headless matplotlib backend, set before any matplotlib import.
@@ -32,9 +37,8 @@ if str(_SRC) not in sys.path:
32
  sys.path.insert(0, str(_SRC))
33
 
34
  # 3) Hint to the GUI that we want frugal defaults on a free-tier
35
- # container (smaller default simulation + a single figure rendered
36
- # only on the active tab). Set via env so the GUI module stays
37
- # deployment-agnostic.
38
  os.environ.setdefault("CDPR_GUI_FRUGAL", "1")
39
 
40
  # 4) Default backend URL for the future variant of the GUI that talks
@@ -42,5 +46,26 @@ os.environ.setdefault("CDPR_GUI_FRUGAL", "1")
42
  # its own process and ignores this.
43
  os.environ.setdefault("CDPR_BACKEND_URL", "http://localhost:8000")
44
 
45
- # 5) Importing the gui module triggers Streamlit page rendering.
46
- from cdpr.interface import gui # noqa: F401, E402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  which produces a blank page with no Python-level traceback. The
13
  ``Agg`` setting is forced here at the very top of the entry-point so
14
  every later import sees it.
15
+
16
+ If importing the GUI itself fails (a bad commit, a missing extra, a
17
+ syntax error introduced upstream), we render the traceback in the page
18
+ rather than letting Streamlit serve a blank tab.
19
  """
20
 
21
  from __future__ import annotations
22
 
23
  import os
24
  import sys
25
+ import traceback
26
  from pathlib import Path
27
 
28
  # 1) Headless matplotlib backend, set before any matplotlib import.
 
37
  sys.path.insert(0, str(_SRC))
38
 
39
  # 3) Hint to the GUI that we want frugal defaults on a free-tier
40
+ # container (smaller default simulation + lazy per-tab plot render).
41
+ # Set via env so the GUI module stays deployment-agnostic.
 
42
  os.environ.setdefault("CDPR_GUI_FRUGAL", "1")
43
 
44
  # 4) Default backend URL for the future variant of the GUI that talks
 
46
  # its own process and ignores this.
47
  os.environ.setdefault("CDPR_BACKEND_URL", "http://localhost:8000")
48
 
49
+ # 5) Import & render. If anything raises (missing dep, syntax error,
50
+ # config error), show the traceback in the page so the user can see
51
+ # what the worker was unhappy about. Without this guard the worker
52
+ # just dies and the browser shows a blank tab.
53
+ try:
54
+ from cdpr.interface import gui # noqa: F401, E402
55
+ except Exception as exc: # pragma: no cover - last-resort surface
56
+ import streamlit as st
57
+
58
+ try:
59
+ st.set_page_config(page_title="CDPR — load failure", layout="wide")
60
+ except Exception:
61
+ pass
62
+ st.title("CDPR research console — failed to load")
63
+ st.error(
64
+ "The console failed to import. The traceback below tells you "
65
+ "which module/line is at fault."
66
+ )
67
+ st.exception(exc)
68
+ st.code(traceback.format_exc(), language="text")
69
+ # Also write to stderr so the Streamlit Cloud "manage app" log
70
+ # carries the same trace.
71
+ print(traceback.format_exc(), file=sys.stderr, flush=True)