From 204126513c8f33030ed37772f5ac38b2e5e81285 Mon Sep 17 00:00:00 2001 From: Marco Wittwer Date: Tue, 10 Nov 2026 03:43:20 +0100 Subject: [PATCH 1/2] fix: preserve hidden inputs and fallback freshness --- README.md | 4 +- app.py | 66 +++++++++++++++++++------- app_helpers.py | 10 +++- tests/test_app_helpers.py | 9 ++++ tests/test_app_render.py | 99 ++++++++++++++++++++++++++++++++++++++- 5 files changed, 167 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 6d7e4ae..f866d9d 100644 --- a/README.md +++ b/README.md @@ -196,8 +196,8 @@ The web app is a full GUI with live preview: | Feature | Description | |---|---| | ๐ŸŒ **English / German** | Switch the interface language in the sidebar at any time | -| ๐Ÿ“‚ **File upload** | Upload one or **several** STL models straight from the sidebar. Without an upload, *Generate* takes a `figure.stl` from the working directory, like the CLI | -| ๐Ÿชž **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live โ€” without running the pipeline. After a run the viewer shows that result until you generate again; if settings or uploads have changed since, a warning says it is out of date | +| ๐Ÿ“‚ **File upload** | Upload one or **several** STL models straight from the sidebar. Without an upload, *Generate* takes a `figure.stl` from the working directory, like the CLI; replacing or removing that file marks an earlier result as out of date | +| ๐Ÿชž **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live โ€” without running the pipeline. Flat surfaces and other files without volume are skipped with a warning. After a run the viewer shows that result until you generate again; if settings or inputs have changed since, a warning says it is out of date | | ๐Ÿงฉ **Auto arrangement** | Multiple figures are placed without collisions (`compact` / `horizontal` / `vertical`) with an adjustable gap โ€” it follows the wall thickness until you set it yourself | | ๐ŸŽš๏ธ **Interactive parameters** | Clearance, wall thickness, insert depth and voxel resolution via sliders | | ๐ŸŽฏ **Manual positioning** | Move each figure (or all of them together) in X/Y/Z inside the box, in steps of 1, 5 or 10 mm | diff --git a/app.py b/app.py index 018afb4..97e3d5d 100644 --- a/app.py +++ b/app.py @@ -224,6 +224,20 @@ def log(self, msg, t0=None): } st.session_state["_hash_by_file_id"] = content_hashes +# The fallback file has no upload id. Hash it on every rerun so replacing or +# removing it changes the staleness snapshot just like an uploaded input. +fallback_path = inlayer.DEFAULT_INPUT +fallback_hash = ( + app_helpers.file_hash(fallback_path) + if not uploaded_files and os.path.isfile(fallback_path) + else None +) +input_snapshot = ( + [(uf.name, content_hashes[uf.file_id]) for uf in uploaded_files] + if uploaded_files + else [(fallback_path, fallback_hash)] if fallback_hash is not None else [] +) + # --- Per-figure state ------------------------------------------------------- # Deliberately right after the upload: the finger recess controls sit further # up the sidebar than the manual offsets and already address single figures. @@ -281,6 +295,17 @@ def _select(label: str, labels: dict, key: str, default, **kwargs): ) +def _persistent_number(widget, label: str, key: str, default: float, **kwargs): + """Numeric widget whose value survives Streamlit dropping a hidden widget.""" + stored_key = f"_{key}_value" + st.session_state.setdefault(stored_key, default) + if key not in st.session_state: + st.session_state[key] = st.session_state[stored_key] + value = widget(label, key=key, **kwargs) + st.session_state[stored_key] = value + return value + + def _step_select(label: str, options: list[float], unit: str, step_key: str) -> float: """Step size of the offset or rotation sliders.""" return float(_select(label, {x: f"{int(x)}{unit}" for x in options}, @@ -441,14 +466,13 @@ def _figure_select(label: str, sel_key: str): finger_recess_axis = inlayer.Config.finger_recess_axis finger_recess_z_offset = inlayer.Config.finger_recess_z_offset if enable_finger_recesses: - finger_radius = st.sidebar.slider( - t("app.finger.radius.label"), + finger_radius = _persistent_number( + st.sidebar.slider, t("app.finger.radius.label"), "finger_radius", + inlayer.Config.finger_radius, min_value=5.0, max_value=15.0, - value=inlayer.Config.finger_radius, step=0.5, help=t("app.finger.radius.help"), - key="finger_radius", ) finger_recess_axis = _select( t("app.finger.axis.label"), @@ -456,14 +480,13 @@ def _figure_select(label: str, sel_key: str): inlayer.Config.finger_recess_axis, help=t("app.finger.axis.help"), ) - finger_recess_z_offset = st.sidebar.slider( - t("app.finger.z_offset.label"), + finger_recess_z_offset = _persistent_number( + st.sidebar.slider, t("app.finger.z_offset.label"), "finger_z_offset", + inlayer.Config.finger_recess_z_offset, min_value=0.0, max_value=30.0, - value=inlayer.Config.finger_recess_z_offset, step=0.5, help=t("app.finger.z_offset.help"), - key="finger_z_offset", ) # Position along the figure. Unlike radius, axis and depth this one is # stored per figure: the best grip point follows the figure's shape, so one @@ -505,11 +528,23 @@ def _figure_select(label: str, sel_key: str): box_diameter = None if use_custom_box: if box_shape == "cylinder": - box_diameter = st.sidebar.number_input(t("app.box.diameter.label"), min_value=10.0, max_value=300.0, value=50.0, step=5.0, key="box_diameter") + box_diameter = _persistent_number( + st.sidebar.number_input, t("app.box.diameter.label"), "box_diameter", 50.0, + min_value=10.0, max_value=300.0, step=5.0, + ) else: - box_width = st.sidebar.number_input(t("app.box.width.label"), min_value=10.0, max_value=300.0, value=50.0, step=5.0, key="box_width") - box_depth = st.sidebar.number_input(t("app.box.depth.label"), min_value=10.0, max_value=300.0, value=50.0, step=5.0, key="box_depth") - box_height = st.sidebar.number_input(t("app.box.height.label"), min_value=5.0, max_value=200.0, value=20.0, step=2.0, key="box_height") + box_width = _persistent_number( + st.sidebar.number_input, t("app.box.width.label"), "box_width", 50.0, + min_value=10.0, max_value=300.0, step=5.0, + ) + box_depth = _persistent_number( + st.sidebar.number_input, t("app.box.depth.label"), "box_depth", 50.0, + min_value=10.0, max_value=300.0, step=5.0, + ) + box_height = _persistent_number( + st.sidebar.number_input, t("app.box.height.label"), "box_height", 20.0, + min_value=5.0, max_value=200.0, step=2.0, + ) st.sidebar.markdown("---") st.sidebar.markdown(t("app.position.heading")) @@ -654,7 +689,7 @@ def _params_snapshot() -> dict: enable_parallel is left out on purpose - it only changes the runtime. """ return { - "files": [(uf.name, content_hashes[uf.file_id]) for uf in uploaded_files], + "files": input_snapshot, "clearance": clearance, "wall_thickness": wall_thickness, "depth_fraction": depth_fraction, @@ -691,7 +726,6 @@ def _params_snapshot() -> dict: tmp_paths: list[str] = [] try: # Input: the uploads, or the default file next to the app - fallback_path = inlayer.DEFAULT_INPUT input_paths: list[str] = [] file_names: list[str] = [] file_hashes: list[str] = [] @@ -709,10 +743,10 @@ def _params_snapshot() -> dict: input_paths.append(tmp_paths[-1]) file_names.append(_labels[uf.file_id]) file_hashes.append(content_hashes[uf.file_id]) - elif os.path.isfile(fallback_path): + elif fallback_hash is not None: input_paths = [fallback_path] file_names = [fallback_path] - file_hashes = [app_helpers.file_hash(fallback_path)] + file_hashes = [fallback_hash] else: st.error(t("app.error.no_input", path=fallback_path)) st.stop() diff --git a/app_helpers.py b/app_helpers.py index a91da05..bdcaab8 100644 --- a/app_helpers.py +++ b/app_helpers.py @@ -29,6 +29,7 @@ import io +import numpy as np import trimesh import inlayer @@ -169,12 +170,17 @@ def preview_copy(mesh: trimesh.Trimesh, face_count: int) -> trimesh.Trimesh: def load_preview_mesh(data: bytes, scale: float, name: str) -> trimesh.Trimesh: """Loads an uploaded STL, decimated for the instant preview. - Raises ValueError naming the file if it holds no triangles (same loader as - the pipeline, so preview and run reject the same files). + Raises ValueError naming the file if it holds no triangles or no volume. + Flat surfaces therefore produce a preview warning instead of a mesh that + the generation step would reject later. """ mesh = inlayer.load_mesh(io.BytesIO(data), name, file_type="stl") if scale != 1.0: mesh.apply_scale(scale) + with np.errstate(invalid="ignore"): + has_volume = abs(mesh.volume) > 0 + if not (mesh.area > 0) or not has_volume: + raise ValueError(t("error.not_solid", name=name)) mesh = decimate_mesh(mesh, PREVIEW_FACE_BUDGET) if not (mesh.area > 0): raise ValueError(t("error.not_solid", name=name)) diff --git a/tests/test_app_helpers.py b/tests/test_app_helpers.py index 036b930..15de12d 100644 --- a/tests/test_app_helpers.py +++ b/tests/test_app_helpers.py @@ -212,6 +212,15 @@ def test_large_mesh_is_decimated(self): out = app_helpers.load_preview_mesh(data, 1.0, "box.stl") assert len(out.faces) < len(sphere.faces) + @pytest.mark.parametrize("angle", [0.0, 30.0]) + def test_flat_surface_names_the_file(self, angle): + """A sheet has area but no volume, in any orientation.""" + sheet = trimesh.creation.box(extents=[10, 10, 0]) + sheet.apply_transform(trimesh.transformations.rotation_matrix(angle, [1, 0, 1])) + data = cast(bytes, sheet.export(file_type="stl")) + with pytest.raises(ValueError, match="sheet.stl has no volume"): + app_helpers.load_preview_mesh(data, 1.0, "sheet.stl") + @pytest.mark.parametrize( "data", [b"", bytes(84), b"solid x\nendsolid x\n", bytes(range(256)) * 2, diff --git a/tests/test_app_render.py b/tests/test_app_render.py index 006e53a..28f5e78 100644 --- a/tests/test_app_render.py +++ b/tests/test_app_render.py @@ -84,11 +84,21 @@ def test_file_of_nan_coordinates_is_skipped_too(self): assert any("nan.stl" in w.value for w in at.warning) assert list(_trace_extents(at)) == ["a.stl"] + def test_flat_surface_is_skipped_with_a_warning(self): + """The preview must reject a sheet just like the generation step.""" + sheet = binary_stl([ + [[0, 0, 0], [10, 0, 0], [10, 10, 0]], + [[0, 0, 0], [10, 10, 0], [0, 10, 0]], + ]) + at = _upload(_run("en"), [("a.stl", _stl([10, 10, 10])), ("sheet.stl", sheet)]) + assert any("sheet.stl has no volume" in w.value for w in at.warning) + assert list(_trace_extents(at)) == ["a.stl"] + class TestFailedRun: """A run that fails says which upload it failed on.""" - # Previews fine, but is no solid: the pipeline refuses it + # Both the preview and the pipeline reject this flat sheet. SHEET = binary_stl([[[0, 0, 0], [10, 0, 0], [10, 10, 0]], [[0, 0, 0], [10, 10, 0], [0, 10, 0]]]) def test_error_names_the_upload_not_its_temp_file(self): @@ -182,6 +192,32 @@ def test_figure_stl_in_the_working_directory_is_used(self, tmp_path, monkeypatch assert at.session_state["result"]["file_names"] == ["figure.stl"] assert (tmp_path / "figure.stl").exists() # only temporary upload files are cleaned up + def test_fallback_change_and_removal_mark_result_stale(self, tmp_path, monkeypatch): + """The actual fallback input belongs in the freshness snapshot.""" + monkeypatch.chdir(tmp_path) + path = tmp_path / "figure.stl" + path.write_bytes(_stl([10, 10, 10])) + at = _run("en") + _widget(at, "slider", "voxel_pitch").set_value(1.0).run() + at.button[0].click().run() + assert not at.exception and not at.error + result = at.session_state["result"] + old_hash = app_helpers.file_hash(str(path)) + assert result["params"]["files"] == [("figure.stl", old_hash)] + assert not _warned(at, "app.results.stale") + + path.write_bytes(_stl([20, 10, 10])) + assert app_helpers.file_hash(str(path)) != old_hash + at.run() + assert _warned(at, "app.results.stale") + assert at.session_state["result"]["params"]["files"] == [("figure.stl", old_hash)] + + path.unlink() + at.run() + assert not at.exception + assert _warned(at, "app.results.stale") + assert at.session_state["result"]["params"]["files"] == [("figure.stl", old_hash)] + class TestCacheIdentity: """Process-wide caches are keyed by content, never by name and size.""" @@ -205,6 +241,67 @@ def test_replacing_a_file_of_the_same_size_marks_the_result_stale(self): assert _warned(at, "app.results.stale") +class TestHiddenNumericValues: + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_values_survive_hiding_and_shape_changes_and_reach_config(self, lang, monkeypatch): + """Optional numeric controls must keep their values and use them on a run.""" + at = _upload(_run(lang), [("cube.stl", _stl([10, 10, 10]))]) + _widget(at, "checkbox", "finger_enabled").check().run() + _widget(at, "slider", "finger_radius").set_value(12.0).run() + _widget(at, "slider", "finger_z_offset").set_value(7.0).run() + _widget(at, "selectbox", "_w_finger_axis").set_value("y").run() + + _widget(at, "checkbox", "use_custom_box").check().run() + _widget(at, "number_input", "box_width").set_value(75.0).run() + _widget(at, "number_input", "box_depth").set_value(65.0).run() + _widget(at, "number_input", "box_height").set_value(30.0).run() + _widget(at, "selectbox", "_w_box_shape").set_value("cylinder").run() + assert _widget(at, "number_input", "box_height").value == 30.0 + _widget(at, "number_input", "box_diameter").set_value(80.0).run() + _widget(at, "selectbox", "_w_box_shape").set_value("box").run() + assert _widget(at, "number_input", "box_width").value == 75.0 + assert _widget(at, "number_input", "box_depth").value == 65.0 + assert _widget(at, "number_input", "box_height").value == 30.0 + _widget(at, "selectbox", "_w_box_shape").set_value("cylinder").run() + assert _widget(at, "number_input", "box_diameter").value == 80.0 + _widget(at, "selectbox", "_w_box_shape").set_value("box").run() + + _widget(at, "checkbox", "finger_enabled").uncheck().run() + _widget(at, "checkbox", "use_custom_box").uncheck().run() + assert at.session_state["_finger_radius_value"] == 12.0 + assert at.session_state["_finger_z_offset_value"] == 7.0 + assert at.session_state["_box_width_value"] == 75.0 + assert at.session_state["_box_depth_value"] == 65.0 + assert at.session_state["_box_height_value"] == 30.0 + assert at.session_state["_box_diameter_value"] == 80.0 + _widget(at, "checkbox", "finger_enabled").check().run() + _widget(at, "checkbox", "use_custom_box").check().run() + assert _widget(at, "slider", "finger_radius").value == 12.0 + assert _widget(at, "slider", "finger_z_offset").value == 7.0 + assert _widget(at, "selectbox", "_w_finger_axis").value == "y" + assert _widget(at, "number_input", "box_width").value == 75.0 + assert _widget(at, "number_input", "box_depth").value == 65.0 + assert _widget(at, "number_input", "box_height").value == 30.0 + + captured = [] + + def capture_config(_figures, config, **_kwargs): + captured.append(config) + raise ValueError("config captured") + + monkeypatch.setattr(inlayer, "build_inlay", capture_config) + _widget(at, "slider", "voxel_pitch").set_value(1.0).run() + at.button[0].click().run() + assert not at.exception + (config,) = captured + assert config.enable_finger_recesses is True + assert (config.finger_radius, config.finger_recess_axis, config.finger_recess_z_offset) == (12.0, "y", 7.0) + assert (config.box_shape, config.box_width, config.box_depth, config.box_height) == ( + "box", 75.0, 65.0, 30.0, + ) + assert config.box_diameter is None + + class TestRotationStepSurvivesHiding: """Streamlit drops a widget's state while it is not rendered (review B19). From f1c963e939218df9f53c3c09d0416697e82b7e27 Mon Sep 17 00:00:00 2001 From: Rigare <19714539+Rigare@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:46:14 +0000 Subject: [PATCH 2/2] fix: finish hidden input persistence and fallback checks --- README.md | 8 +- app.py | 21 ++-- app_helpers.py | 11 +-- tests/test_app_helpers.py | 18 ++-- tests/test_app_render.py | 196 ++++++++++++++++++++++++++++++++------ 5 files changed, 202 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index f866d9d..c363d49 100644 --- a/README.md +++ b/README.md @@ -197,14 +197,14 @@ The web app is a full GUI with live preview: |---|---| | ๐ŸŒ **English / German** | Switch the interface language in the sidebar at any time | | ๐Ÿ“‚ **File upload** | Upload one or **several** STL models straight from the sidebar. Without an upload, *Generate* takes a `figure.stl` from the working directory, like the CLI; replacing or removing that file marks an earlier result as out of date | -| ๐Ÿชž **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live โ€” without running the pipeline. Flat surfaces and other files without volume are skipped with a warning. After a run the viewer shows that result until you generate again; if settings or inputs have changed since, a warning says it is out of date | +| ๐Ÿชž **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live โ€” without running the pipeline. This lightweight preview can show flat surfaces; *Generate* checks whether a model can form a solid. After a run the viewer shows that result until you generate again; if settings or inputs have changed since, a warning says it is out of date | | ๐Ÿงฉ **Auto arrangement** | Multiple figures are placed without collisions (`compact` / `horizontal` / `vertical`) with an adjustable gap โ€” it follows the wall thickness until you set it yourself | | ๐ŸŽš๏ธ **Interactive parameters** | Clearance, wall thickness, insert depth and voxel resolution via sliders | | ๐ŸŽฏ **Manual positioning** | Move each figure (or all of them together) in X/Y/Z inside the box, in steps of 1, 5 or 10 mm | | ๐Ÿ”„ **Manual rotation** | Rotate each figure (or all of them together) about X/Y/Z, in steps of 1, 5, 10 or 45ยฐ | -| ๐Ÿ–๏ธ **Finger recesses** | Optional hemispherical cut-outs beside each figure as a removal aid (adjustable radius, axis and depth; the position along the figure is set **per figure**) | +| ๐Ÿ–๏ธ **Finger recesses** | Optional hemispherical cut-outs beside each figure as a removal aid (adjustable radius, axis and depth; the position along the figure is set **per figure**). Settings survive switching recesses off and on | | โšก **Multi-threading** | Optionally process several figures in parallel across CPU cores (checkbox in the sidebar) | -| ๐Ÿ“ **Box overrides** | Optionally force fixed box dimensions | +| ๐Ÿ“ **Box overrides** | Optionally force fixed box dimensions; dimensions survive switching overrides off and on or changing the box shape | | ๐Ÿงท **Settings per file** | Offsets, rotations and grip positions belong to each upload โ€” two files with the same name appear as `model.stl` and `model.stl (2)` and are positioned separately; a removed file takes its settings along | | ๐Ÿ” **Wall check** | Every wall is measured on the finished geometry โ€” sides, floor and the walls between cavities; each finding names its figure | | ๐Ÿ‘๏ธ **3D preview** | Interactive Plotly viewer (rotate, zoom, show/hide) | @@ -533,7 +533,7 @@ value as a usage error before any work starts. - **Cavities stay open:** each cavity is extruded up through the top face. With `depth_fraction = 1.0` and a negative Z offset the pocket used to close at the top โ€” a sealed void in the print. - **Repair only when needed:** `prepare_figure` skips `pymeshfix` when the loaded mesh is already watertight **and** consistently wound โ€” the normal case for cleanly exported STLs. That halves the step's runtime (measured 1.99 s โ†’ 1.08 s at 82k triangles) and does not change the geometry. Watertightness alone is not a sufficient criterion: a mesh with inverted faces is watertight but would corrupt the subsequent voxel fill. When the repair does run, it keeps **every** shell of the file: pymeshfix's default drops all but the shell with the most triangles, so a miniature with a separate base used to lose the base as soon as the file had a single hole anywhere. - **Low-poly meshes:** input meshes are voxelised by sampling each triangle in rows along its longest edge, so the cost follows the surface area. trimesh's own voxeliser subdivides until *every* edge is below `voxel_pitch / 2`, which costs (edge length / pitch)ยฒ per triangle โ€” the long, thin triangles of CAD exports (rods, pins, profiles) took gigabytes or aborted with "max_iter exceeded". The same sampler now voxelizes the later steps too and works in batches: the tolerance offset used to be the memory peak of a run (3.8 GB for a 60 mm cube at the default settings, more than 10 GB for 100 mm) and now needs roughly an eighth of that (0.5 GB and 1.3 GB), the step itself a third of the time. Cavities can differ from earlier versions by a few hundredths of a millimetre. A figure whose voxel grid would exceed `MAX_GRID_VOXELS` (10โน voxels at `voxel_pitch / 2`, the finest grid in the pipeline) is refused with a message suggesting a larger pitch, instead of exhausting the machine's memory. The bound is checked wherever a grid is built โ€” on the upload, on the rotated figure plus its clearance padding, and on every cutter โ€” so neither a rotation nor a large Z offset slips past it. -- **Broken files:** an empty or unreadable STL is rejected with a message naming the file (in the web app: the upload, not the temporary file it is read from). So is a file whose coordinates are all NaN or infinite, and one without volume โ€” a flat surface or triangles collapsed to a line cannot be closed into a solid. In the web app the instant preview skips such a file with a warning and still shows the others. +- **Broken files:** an empty or unreadable STL is rejected with a message naming the file (in the web app: the upload, not the temporary file it is read from). So is a file whose coordinates are all NaN or infinite. The instant preview skips files without usable triangles or area with a warning and still shows the others. A flat surface with nonzero area can appear in this lightweight preview; generation rejects it if mesh repair cannot turn it into a solid. - **Wall check:** measured exactly on the meshes (manifold3d) while `build_inlay` still has every figure's cutter: side and floor walls per figure, the wall between each pair of cavities, sealed voids and figures without a cavity. Each finding names its figure; `passes_min_wall` is true only without any finding. The tolerance is 0.05 mm (float rounding, the cylinder's chord error). The earlier voxel-based check overestimated walls by up to one pitch, ignored the walls between cavities and passed an inlay without any cavity. --- diff --git a/app.py b/app.py index 97e3d5d..af56714 100644 --- a/app.py +++ b/app.py @@ -227,11 +227,14 @@ def log(self, msg, t0=None): # The fallback file has no upload id. Hash it on every rerun so replacing or # removing it changes the staleness snapshot just like an uploaded input. fallback_path = inlayer.DEFAULT_INPUT -fallback_hash = ( - app_helpers.file_hash(fallback_path) - if not uploaded_files and os.path.isfile(fallback_path) - else None -) +fallback_hash = None +fallback_read_error = None +if not uploaded_files and os.path.isfile(fallback_path): + try: + fallback_hash = app_helpers.file_hash(fallback_path) + except OSError as error: + # An unavailable input marks old results stale; Generate reports why. + fallback_read_error = error input_snapshot = ( [(uf.name, content_hashes[uf.file_id]) for uf in uploaded_files] if uploaded_files @@ -301,7 +304,11 @@ def _persistent_number(widget, label: str, key: str, default: float, **kwargs): st.session_state.setdefault(stored_key, default) if key not in st.session_state: st.session_state[key] = st.session_state[stored_key] - value = widget(label, key=key, **kwargs) + value = widget( + label, key=key, + on_change=lambda: st.session_state.update({stored_key: st.session_state[key]}), + **kwargs, + ) st.session_state[stored_key] = value return value @@ -743,6 +750,8 @@ def _params_snapshot() -> dict: input_paths.append(tmp_paths[-1]) file_names.append(_labels[uf.file_id]) file_hashes.append(content_hashes[uf.file_id]) + elif fallback_read_error is not None: + raise fallback_read_error elif fallback_hash is not None: input_paths = [fallback_path] file_names = [fallback_path] diff --git a/app_helpers.py b/app_helpers.py index bdcaab8..8c5f6ae 100644 --- a/app_helpers.py +++ b/app_helpers.py @@ -29,7 +29,6 @@ import io -import numpy as np import trimesh import inlayer @@ -170,17 +169,13 @@ def preview_copy(mesh: trimesh.Trimesh, face_count: int) -> trimesh.Trimesh: def load_preview_mesh(data: bytes, scale: float, name: str) -> trimesh.Trimesh: """Loads an uploaded STL, decimated for the instant preview. - Raises ValueError naming the file if it holds no triangles or no volume. - Flat surfaces therefore produce a preview warning instead of a mesh that - the generation step would reject later. + Rejects unreadable files and meshes without usable triangles or area, + naming the upload. Flat surfaces can appear here; only generation repairs + the mesh and checks whether it can form a solid. """ mesh = inlayer.load_mesh(io.BytesIO(data), name, file_type="stl") if scale != 1.0: mesh.apply_scale(scale) - with np.errstate(invalid="ignore"): - has_volume = abs(mesh.volume) > 0 - if not (mesh.area > 0) or not has_volume: - raise ValueError(t("error.not_solid", name=name)) mesh = decimate_mesh(mesh, PREVIEW_FACE_BUDGET) if not (mesh.area > 0): raise ValueError(t("error.not_solid", name=name)) diff --git a/tests/test_app_helpers.py b/tests/test_app_helpers.py index 15de12d..204d549 100644 --- a/tests/test_app_helpers.py +++ b/tests/test_app_helpers.py @@ -212,14 +212,18 @@ def test_large_mesh_is_decimated(self): out = app_helpers.load_preview_mesh(data, 1.0, "box.stl") assert len(out.faces) < len(sphere.faces) - @pytest.mark.parametrize("angle", [0.0, 30.0]) - def test_flat_surface_names_the_file(self, angle): - """A sheet has area but no volume, in any orientation.""" - sheet = trimesh.creation.box(extents=[10, 10, 0]) - sheet.apply_transform(trimesh.transformations.rotation_matrix(angle, [1, 0, 1])) + @pytest.mark.parametrize("angle", [0.0, np.pi / 4]) + def test_flat_surface_can_be_previewed(self, angle): + """Preview checks usable area; generation decides whether it forms a solid.""" + sheet = trimesh.Trimesh( + vertices=[[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0]], + faces=[[0, 1, 2], [0, 2, 3]], + ) + sheet.apply_transform(trimesh.transformations.rotation_matrix(angle, [1, 1, 1])) data = cast(bytes, sheet.export(file_type="stl")) - with pytest.raises(ValueError, match="sheet.stl has no volume"): - app_helpers.load_preview_mesh(data, 1.0, "sheet.stl") + out = app_helpers.load_preview_mesh(data, 1.0, "sheet.stl") + assert len(out.faces) == 2 + assert out.area == pytest.approx(100.0) @pytest.mark.parametrize( "data", diff --git a/tests/test_app_render.py b/tests/test_app_render.py index 28f5e78..008602c 100644 --- a/tests/test_app_render.py +++ b/tests/test_app_render.py @@ -14,6 +14,7 @@ import base64 import json from pathlib import Path +from typing import cast import numpy as np import pytest @@ -36,7 +37,7 @@ def _run(lang: str) -> AppTest: def _stl(extents) -> bytes: - return trimesh.creation.box(extents=extents).export(file_type="stl") + return cast(bytes, trimesh.creation.box(extents=extents).export(file_type="stl")) def _upload(at: AppTest, files: list[tuple[str, bytes]]) -> AppTest: @@ -53,7 +54,7 @@ def _checkbox(at: AppTest, key: str): def _warned(at: AppTest, key: str) -> bool: """Whether a warning with that text is shown (Streamlit strips a leading emoji).""" - text = i18n.TRANSLATIONS[key][i18n.get_language()] + text = i18n.TRANSLATIONS[key][at.session_state["ui_lang"]] return any(w.value.strip() and w.value.strip() in text for w in at.warning) @@ -84,31 +85,39 @@ def test_file_of_nan_coordinates_is_skipped_too(self): assert any("nan.stl" in w.value for w in at.warning) assert list(_trace_extents(at)) == ["a.stl"] - def test_flat_surface_is_skipped_with_a_warning(self): - """The preview must reject a sheet just like the generation step.""" - sheet = binary_stl([ + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_flat_surface_is_drawn_without_validating_a_solid(self, lang): + """The lightweight preview can draw a sheet; generation validates solids.""" + triangles = np.array([ [[0, 0, 0], [10, 0, 0], [10, 10, 0]], [[0, 0, 0], [10, 10, 0], [0, 10, 0]], ]) - at = _upload(_run("en"), [("a.stl", _stl([10, 10, 10])), ("sheet.stl", sheet)]) - assert any("sheet.stl has no volume" in w.value for w in at.warning) - assert list(_trace_extents(at)) == ["a.stl"] + transform = trimesh.transformations.rotation_matrix(np.pi / 4, [1, 1, 1]) + rotated = trimesh.transformations.transform_points(triangles.reshape(-1, 3), transform) + sheet = binary_stl(rotated.reshape(-1, 3, 3)) + at = _upload(_run(lang), [("a.stl", _stl([10, 10, 10])), ("sheet.stl", sheet)]) + assert not at.warning + assert list(_trace_extents(at)) == ["a.stl", "sheet.stl"] class TestFailedRun: """A run that fails says which upload it failed on.""" - # Both the preview and the pipeline reject this flat sheet. + # A flat sheet can be previewed, but cannot be repaired into a solid. SHEET = binary_stl([[[0, 0, 0], [10, 0, 0], [10, 10, 0]], [[0, 0, 0], [10, 10, 0], [0, 10, 0]]]) - def test_error_names_the_upload_not_its_temp_file(self): + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_error_names_the_upload_not_its_temp_file(self, lang): """The run reads uploads from temporary files and the message named those: "/tmp/tmpk3x9.stl contains no triangles" - which of two uploads?""" - at = _upload(_run("en"), [("good.stl", _stl([10, 10, 10])), ("sheet.stl", self.SHEET)]) + at = _upload(_run(lang), [("good.stl", _stl([10, 10, 10])), ("sheet.stl", self.SHEET)]) + assert not at.warning + assert list(_trace_extents(at)) == ["good.stl", "sheet.stl"] _widget(at, "slider", "voxel_pitch").set_value(1.0).run() at.button[0].click().run() (message,) = [e.value for e in at.error] - assert "sheet.stl has no volume" in message + expected = i18n.TRANSLATIONS["error.not_solid"][lang].format(name="sheet.stl") + assert expected in message assert "tmp" not in message # The message is the whole story - no stack trace below it assert not at.exception @@ -192,31 +201,105 @@ def test_figure_stl_in_the_working_directory_is_used(self, tmp_path, monkeypatch assert at.session_state["result"]["file_names"] == ["figure.stl"] assert (tmp_path / "figure.stl").exists() # only temporary upload files are cleaned up - def test_fallback_change_and_removal_mark_result_stale(self, tmp_path, monkeypatch): + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_fallback_change_and_removal_mark_result_stale(self, lang, tmp_path, monkeypatch): """The actual fallback input belongs in the freshness snapshot.""" monkeypatch.chdir(tmp_path) path = tmp_path / "figure.stl" path.write_bytes(_stl([10, 10, 10])) - at = _run("en") + at = _run(lang) _widget(at, "slider", "voxel_pitch").set_value(1.0).run() at.button[0].click().run() assert not at.exception and not at.error result = at.session_state["result"] + old_extent = result["fig_viz"][0].extents[0] old_hash = app_helpers.file_hash(str(path)) assert result["params"]["files"] == [("figure.stl", old_hash)] assert not _warned(at, "app.results.stale") path.write_bytes(_stl([20, 10, 10])) - assert app_helpers.file_hash(str(path)) != old_hash + new_hash = app_helpers.file_hash(str(path)) + assert new_hash != old_hash at.run() assert _warned(at, "app.results.stale") assert at.session_state["result"]["params"]["files"] == [("figure.stl", old_hash)] + at.button[0].click().run() + assert not at.exception and not at.error + result = at.session_state["result"] + assert result["params"]["files"] == [("figure.stl", new_hash)] + assert result["fig_viz"][0].extents[0] == pytest.approx(old_extent + 10.0) + assert not _warned(at, "app.results.stale") + path.unlink() at.run() assert not at.exception assert _warned(at, "app.results.stale") - assert at.session_state["result"]["params"]["files"] == [("figure.stl", old_hash)] + assert at.session_state["result"]["params"]["files"] == [("figure.stl", new_hash)] + at.button[0].click().run() + assert not at.exception + assert [e.value for e in at.error] == [ + i18n.TRANSLATIONS["app.error.no_input"][lang].format(path="figure.stl") + ] + assert "result" not in at.session_state + + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_upload_supersedes_fallback_and_ignores_its_changes(self, lang, tmp_path, monkeypatch): + """An uploaded figure.stl is independent of the same-named fallback file.""" + monkeypatch.chdir(tmp_path) + path = tmp_path / "figure.stl" + path.write_bytes(_stl([10, 10, 10])) + at = _run(lang) + _widget(at, "slider", "voxel_pitch").set_value(1.0).run() + at.button[0].click().run() + fallback_extent = at.session_state["result"]["fig_viz"][0].extents[0] + + upload = _stl([20, 10, 10]) + _upload(at, [("figure.stl", upload)]) + assert _warned(at, "app.results.stale") + at.button[0].click().run() + assert not at.exception and not at.error + result = at.session_state["result"] + assert result["params"]["files"] == [("figure.stl", app_helpers.bytes_hash(upload))] + assert result["fig_viz"][0].extents[0] == pytest.approx(fallback_extent + 10.0) + assert not _warned(at, "app.results.stale") + + path.write_bytes(_stl([30, 10, 10])) + at.run() + assert not at.exception + assert not _warned(at, "app.results.stale") + path.unlink() + at.run() + assert not at.exception + assert not _warned(at, "app.results.stale") + + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_unreadable_fallback_marks_result_stale_and_reports_run_error( + self, lang, tmp_path, monkeypatch + ): + """Read errors during freshness checks must not abort an ordinary rerender.""" + monkeypatch.chdir(tmp_path) + (tmp_path / "figure.stl").write_bytes(_stl([10, 10, 10])) + at = _run(lang) + _widget(at, "slider", "voxel_pitch").set_value(1.0).run() + at.button[0].click().run() + old_files = at.session_state["result"]["params"]["files"] + + def unreadable(_path): + raise PermissionError("fallback read denied") + + monkeypatch.setattr(app_helpers, "file_hash", unreadable) + at.run() + assert not at.exception + assert _warned(at, "app.results.stale") + assert at.session_state["result"]["params"]["files"] == old_files + + at.button[0].click().run() + assert not at.exception + assert [e.value for e in at.error] == [ + i18n.TRANSLATIONS["app.error.failed"][lang].format(error="fallback read denied") + ] + assert "result" not in at.session_state class TestCacheIdentity: @@ -242,6 +325,32 @@ def test_replacing_a_file_of_the_same_size_marks_the_result_stale(self): class TestHiddenNumericValues: + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + @pytest.mark.parametrize( + "kind,key,toggle,value", + [ + ("slider", "finger_radius", "finger_enabled", 12.0), + ("slider", "finger_z_offset", "finger_enabled", 7.0), + ("number_input", "box_width", "use_custom_box", 75.0), + ("number_input", "box_depth", "use_custom_box", 65.0), + ("number_input", "box_height", "use_custom_box", 30.0), + ("number_input", "box_diameter", "use_custom_box", 80.0), + ], + ) + def test_edit_and_hide_in_one_rerun_preserves_value(self, lang, kind, key, toggle, value): + """An edit must persist even when the same event batch hides its widget.""" + at = _run(lang) + if key == "box_diameter": + _widget(at, "selectbox", "_w_box_shape").set_value("cylinder").run() + _widget(at, "checkbox", toggle).check().run() + _widget(at, kind, key).set_value(value) + _widget(at, "checkbox", toggle).uncheck().run() + assert not at.exception + assert at.session_state[f"_{key}_value"] == value + _widget(at, "checkbox", toggle).check().run() + assert not at.exception + assert _widget(at, kind, key).value == value + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) def test_values_survive_hiding_and_shape_changes_and_reach_config(self, lang, monkeypatch): """Optional numeric controls must keep their values and use them on a run.""" @@ -255,6 +364,14 @@ def test_values_survive_hiding_and_shape_changes_and_reach_config(self, lang, mo _widget(at, "number_input", "box_width").set_value(75.0).run() _widget(at, "number_input", "box_depth").set_value(65.0).run() _widget(at, "number_input", "box_height").set_value(30.0).run() + other_lang = next(code for code in i18n.LANGUAGES if code != lang) + _widget(at, "selectbox", "ui_lang").set_value(other_lang).run() + assert not at.exception + assert _widget(at, "slider", "finger_radius").value == 12.0 + assert _widget(at, "slider", "finger_z_offset").value == 7.0 + assert _widget(at, "number_input", "box_width").value == 75.0 + assert _widget(at, "number_input", "box_depth").value == 65.0 + assert _widget(at, "number_input", "box_height").value == 30.0 _widget(at, "selectbox", "_w_box_shape").set_value("cylinder").run() assert _widget(at, "number_input", "box_height").value == 30.0 _widget(at, "number_input", "box_diameter").set_value(80.0).run() @@ -266,14 +383,40 @@ def test_values_survive_hiding_and_shape_changes_and_reach_config(self, lang, mo assert _widget(at, "number_input", "box_diameter").value == 80.0 _widget(at, "selectbox", "_w_box_shape").set_value("box").run() + captured = [] + + def capture_config(_figures, config, **_kwargs): + captured.append(config) + raise ValueError("config captured") + + monkeypatch.setattr(inlayer, "build_inlay", capture_config) + _widget(at, "slider", "voxel_pitch").set_value(1.0).run() + + def run_config(): + at.button[0].click().run() + assert not at.exception + assert len(captured) == 1 + return captured.pop() + _widget(at, "checkbox", "finger_enabled").uncheck().run() _widget(at, "checkbox", "use_custom_box").uncheck().run() + _widget(at, "selectbox", "ui_lang").set_value(lang).run() + assert not at.exception assert at.session_state["_finger_radius_value"] == 12.0 assert at.session_state["_finger_z_offset_value"] == 7.0 assert at.session_state["_box_width_value"] == 75.0 assert at.session_state["_box_depth_value"] == 65.0 assert at.session_state["_box_height_value"] == 30.0 assert at.session_state["_box_diameter_value"] == 80.0 + config = run_config() + assert config.enable_finger_recesses is False + assert (config.finger_radius, config.finger_recess_axis, config.finger_recess_z_offset) == ( + inlayer.Config.finger_radius, inlayer.Config.finger_recess_axis, + inlayer.Config.finger_recess_z_offset, + ) + assert (config.box_width, config.box_depth, config.box_height, config.box_diameter) == ( + None, None, None, None, + ) _widget(at, "checkbox", "finger_enabled").check().run() _widget(at, "checkbox", "use_custom_box").check().run() assert _widget(at, "slider", "finger_radius").value == 12.0 @@ -283,17 +426,7 @@ def test_values_survive_hiding_and_shape_changes_and_reach_config(self, lang, mo assert _widget(at, "number_input", "box_depth").value == 65.0 assert _widget(at, "number_input", "box_height").value == 30.0 - captured = [] - - def capture_config(_figures, config, **_kwargs): - captured.append(config) - raise ValueError("config captured") - - monkeypatch.setattr(inlayer, "build_inlay", capture_config) - _widget(at, "slider", "voxel_pitch").set_value(1.0).run() - at.button[0].click().run() - assert not at.exception - (config,) = captured + config = run_config() assert config.enable_finger_recesses is True assert (config.finger_radius, config.finger_recess_axis, config.finger_recess_z_offset) == (12.0, "y", 7.0) assert (config.box_shape, config.box_width, config.box_depth, config.box_height) == ( @@ -301,6 +434,15 @@ def capture_config(_figures, config, **_kwargs): ) assert config.box_diameter is None + _widget(at, "selectbox", "_w_box_shape").set_value("cylinder").run() + assert _widget(at, "number_input", "box_diameter").value == 80.0 + assert _widget(at, "number_input", "box_height").value == 30.0 + config = run_config() + assert config.enable_finger_recesses is True + assert (config.finger_radius, config.finger_recess_axis, config.finger_recess_z_offset) == (12.0, "y", 7.0) + assert (config.box_shape, config.box_diameter, config.box_height) == ("cylinder", 80.0, 30.0) + assert (config.box_width, config.box_depth) == (None, None) + class TestRotationStepSurvivesHiding: """Streamlit drops a widget's state while it is not rendered (review B19).