From bd0a7a6b5d96c04ee5d7dad842ae9681968caf8e Mon Sep 17 00:00:00 2001 From: Rigare <19714539+Rigare@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:51:53 +0000 Subject: [PATCH 1/2] feat: reopen versioned projects in web and CLI --- AGENTS.md | 6 +- Dockerfile | 13 +- README.md | 61 +++- app.py | 177 ++++++++-- app_helpers.py | 119 +++++++ i18n.py | 101 ++++++ inlayer.py | 251 ++++++++++---- inlayer_project.py | 416 +++++++++++++++++++++++ tests/test_app_helpers.py | 103 ++++++ tests/test_app_render.py | 186 +++++++++++ tests/test_i18n.py | 2 +- tests/test_project.py | 581 +++++++++++++++++++++++++++++++++ tests/test_streamlit_config.py | 2 +- 13 files changed, 1907 insertions(+), 111 deletions(-) create mode 100644 inlayer_project.py create mode 100644 tests/test_project.py diff --git a/AGENTS.md b/AGENTS.md index f4a09a6..20d96d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,8 @@ High-signal context for OpenCode sessions in this repo. ## Architecture - `inlayer.py` is the pipeline library module. It exposes a frozen `Config` dataclass plus pipeline functions (`apply_euler_rotation`, `prepare_figure`, `dilate`, `build_inlay`, `wall_thickness_stats_3d`; `arrange_footprints` is the layout `build_inlay` uses). All parameters flow through `Config`. -- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`/`bytes_hash`, `quantize_axis_value`, `resolve_selection`, `applied_figure_params`, `figure_labels`, `load_preview_mesh`, `preview_copy`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.) +- `inlayer_project.py` owns the strict, versioned JSON recipe shared by CLI and Web (format `inlayer-project`, version 1): every `Config` field, stable figure ids, full SHA-256 source identities and individual rotations, offsets and grip positions. It imports `Config`; `inlayer.main` imports it lazily to avoid a module cycle. Recipes contain no STL bytes. Matching is by full content hash, never name or upload order; CLI-relative paths start at the recipe directory. Figure offsets are additions to the global `Config.offset_*` and `effective_offsets` combines them exactly once. Web uploads have no persisted local path. Unknown fields and unsupported versions are errors, not migration guesses. +- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`/`bytes_hash`, `quantize_axis_value`, `resolve_selection`, `applied_figure_params`, `project_session_state`, `figure_labels`, `load_preview_mesh`, `preview_copy`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.) - `app.py` is a Streamlit frontend. It builds an `inlayer.Config` from the sidebar widgets and passes it into the pipeline functions (no global mutation). Its widgets start at `Config`'s defaults (`inlayer.Config.`, read the way the CLI reads them), never at literals of their own: `tests/test_app_render.py` checks that the widgets start from `Config`'s values, `tests/test_pipeline.py::TestCLIDefaults` that the parser does. The same goes for a default quoted in a help text - pass it into the translation (`default=Config.`), don't type it into `i18n.py`. - `i18n.py` holds the **bilingual UI** (English/German). `t(key, **kwargs)` looks up `TRANSLATIONS` and fills named placeholders; unknown keys return the key itself rather than raising, so a missing string can never abort a running computation. Keys are namespaced `app.*` / `cli.*` / `pipeline.*` / `config.*` / `error.*` / `check.*` (wall-check findings, shared by CLI and app through `inlayer.describe_violation`). - **The current language is a `ContextVar`, not a module global.** Streamlit runs each session's script in its own thread; a shared global would let one session's language selection bleed into another's. Do not "simplify" this into a plain variable. @@ -48,6 +49,7 @@ High-signal context for OpenCode sessions in this repo. - **`app.py`'s "all figures" sentinel stays untranslated.** `ALL_FIGURES` is a stored session-state value, not display text — translating it would invalidate the saved selection on a language switch. It is rendered through `format_func` (`_fig_label`) instead. The same applies to any option value that is persisted rather than merely shown - the figure options are upload ids for the same reason. - **Every widget in `app.py` has a fixed, language-independent `key`.** Streamlit derives an unkeyed widget's identity from its label, which is translated: a language switch created new widgets, the uploads vanished and every setting fell back to its default. `tests/test_app_render.py` fails on a widget call without `key=`. - **Per-figure settings belong to an upload (`UploadedFile.file_id`), not to a file name.** `fig_offsets_dict` is keyed by id; entries of removed uploads are deleted (re-uploading starts from the defaults), duplicate names are shown as `model.stl (2)` (`figure_labels`). Two different `model.stl` files used to share one entry and moved together. +- **Project ids and project hashes are not cache ids.** `project_session_state` maps persistent recipe ids to transient upload ids only once per changed import; `_project_id_by_file_id` retains them for later exports and `_fallback_project_id` identifies the fallback figure. Never serialize an upload id. The existing 16-character `content_hashes` still key caches and freshness; `_project_hash_by_file_id` and `_fallback_project_hash` hold separate full SHA-256 identities for recipes. `_current_config()` is shared by run and export; `_project_config()` additionally retains hidden multi-figure choices without changing the run. - **Selections and sliders are reconciled with the uploads before any widget exists.** All three per-figure controls (recess position, offsets, rotation) resolve their selection through `app_helpers.resolve_selection` and reload their widgets from the stored values whenever the figure they show changes - including a removed upload, a new first figure under "all figures" and widget state dropped while hidden. Don't go back to loading in the selectbox `on_change` only: that missed every change to the file list, and the sliders then showed values the pipeline did not use. - **`app_helpers.applied_figure_params` is the only source of per-figure values.** The run, the instant preview and the staleness snapshot all read it - never a slider, which only shows the selected figure (reading the slider made a mere selection change look like a settings change). - **New user-facing text needs both languages.** `tests/test_i18n.py` fails on a missing translation, on placeholders that differ between languages, on positional `{}` placeholders, and on keys referenced in source but absent from the table. @@ -61,7 +63,7 @@ High-signal context for OpenCode sessions in this repo. - **The wall check is exact and per figure (`_wall_check`).** Each cutter is clipped to the box with manifold3d: side and floor walls come from the pocket's bounds (for the cylinder: apothem minus the farthest vertex), walls between pockets from `min_gap`, sealed voids from negative-volume shells. Findings (`side`, `floor`, `inner`, `merged`, `sealed`, `no_cavity`) carry the figure index. `passes_min_wall` means *no finding at all*; `WALL_TOLERANCE_MM` (0.05) only absorbs float32 rounding and the cylinder's chord error. `wall_thickness_stats_3d(inlay)` just reports it - there is no voxel fallback for meshes that did not come out of `build_inlay`. - **`build_inlay` never rotates.** Rotations are applied in step 1 via `apply_euler_rotation` and are already baked into the meshes handed to `build_inlay`. It used to accept an `individual_rotations` argument that was silently ignored — that parameter is gone; don't reintroduce it. - There are **two entry points:** - - CLI: `python inlayer.py [-i figure.stl] [-o inlay.stl] [-c 0.4] [--lang de] …` — `--lang` is parsed *before* the main parser is built, because argparse renders help strings at construction time; `INLAYER_LANG` is the fallback. + - CLI: `python inlayer.py [-i figure.stl] [-o inlay.stl] [-c 0.4] [--project project.json] [--save-project project.json] [--lang de] …` — `--lang` is parsed *before* the main parser is built, because argparse renders help strings at construction time; `INLAYER_LANG` is the fallback. With `--project`, only input/output paths, `--save-project` and language may override the invocation; configuration flags are usage errors. The CLI is `inlayer.main(argv)` (parser in `_build_parser()`) and returns its exit code; `__main__` is only `sys.exit(main())`. Keep it that way: code under `__main__` cannot be imported, so the tests could only start it as a subprocess and never looked at the STL it wrote. - Web UI: `streamlit run app.py` diff --git a/Dockerfile b/Dockerfile index b0da1b7..88ad910 100644 --- a/Dockerfile +++ b/Dockerfile @@ -26,7 +26,7 @@ FROM base AS test COPY requirements-dev.txt ./ RUN pip install --no-cache-dir -r requirements-dev.txt -COPY pytest.ini inlayer.py app.py app_helpers.py i18n.py ./ +COPY pytest.ini inlayer.py inlayer_project.py app.py app_helpers.py i18n.py ./ COPY tests/ ./tests/ # tests/test_streamlit_config.py reads all of these: the config whose theme and # upload limit it pins down, the Dockerfile itself to verify the runtime @@ -39,14 +39,13 @@ COPY Dockerfile compose.yaml ./ RUN python -m pytest -q -# --- Laufzeit --------------------------------------------------------------- +# --- Runtime --------------------------------------------------------------- FROM base AS runtime -# Anwendungscode kopieren -COPY inlayer.py app.py app_helpers.py i18n.py ./ -# Streamlit-Konfiguration: das Custom-CSS in app.py ist auf das dunkle Theme -# ausgelegt. Ohne diese Datei faellt der Container auf das helle Standard-Theme -# zurueck und Sidebar-Beschriftungen werden unlesbar. +# Copy application modules explicitly, including the shared project format. +COPY inlayer.py inlayer_project.py app.py app_helpers.py i18n.py ./ +# The custom CSS in app.py expects this dark theme. Omitting the configuration +# falls back to the light theme and makes sidebar labels unreadable. COPY .streamlit/ ./.streamlit/ # Nicht als root laufen: der Container haengt am offenen Port und verarbeitet diff --git a/README.md b/README.md index c363d49..df6f73a 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,7 @@ 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 | +| 💾 **Project recipes** | Download and reopen versioned JSON with all settings, stable figure identities and full source hashes. Upload the JSON **and the original STLs** to reopen it; STL bytes are not embedded | | 🪞 **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 | @@ -251,6 +252,15 @@ python inlayer.py -i fig1.stl fig2.stl -o inlay.stl --finger-recesses --finger-r # Process several figures in parallel across CPU cores python inlayer.py -i fig1.stl fig2.stl fig3.stl -o inlay.stl --parallel +# Save a versioned project recipe together with the inlay +python inlayer.py -i fig1.stl fig2.stl -o inlay.stl --save-project project.json + +# Reopen it after a restart; stored source paths are relative to the JSON +python inlayer.py --project project.json -o reopened.stl + +# Reopen a recipe downloaded from the web by supplying the original STLs +python inlayer.py --project project.json -i fig1.stl fig2.stl -o reopened.stl + # German output python inlayer.py --lang de -i figure.stl -o inlay.stl @@ -267,13 +277,60 @@ you can inspect it. |---|---| | `0` | Inlay written, wall check passed | | `1` | The run failed — an unreadable STL, a voxel grid too large for the resolution, a box too small to leave any material, not enough memory. One line on stderr says which; no inlay is written | -| `2` | Invalid arguments (argparse usage error), an input file that does not exist or an output path that cannot be written — nothing was computed | +| `2` | Invalid arguments, an unreadable/incompatible project, a missing or changed source, or an output path that cannot be written — nothing was computed | | `3` | Inlay written, but the wall check found problems | All `--finger-recess-position` values are validated while parsing. Their count (one, or one per `-i` file) only matters with `--finger-recesses`; without it the positions have no effect and a note says so. +### Versioned project recipes (JSON) + +The web app's **Download project as JSON** button and the CLI's +`--save-project PATH` write the same format: `format: "inlayer-project"`, +`version: 1`. A recipe contains every `Config` field and, for each figure, a +stable UUID, its rotation, individual offset and grip position, plus a source +name, an optional path and the **full SHA-256 hash of the source bytes**. The +persistent figure id is independent of a Streamlit upload id, file name or +upload order. Two files both named `model.stl` therefore remain separate when +their content differs. + +**A recipe is not an archive:** it contains no STL bytes and is not a ZIP file. +To reopen a project in the web app, upload its JSON and exactly one original +STL per project figure. The app checks every hash immediately; missing, +changed or additional sources and incompatible settings are reported in the +sidebar, and *Generate* cannot start until the inputs match. Sources are then +put into project order by content hash, never by name. The same recipe can be +exported again with the same stable ids. Disabled per-figure features are +saved with their effective zero values. + +For the CLI, relative source paths are resolved from the **recipe's directory**, +not the process's working directory. Web exports deliberately have no local +paths, so pass their original STLs with `-i` when opening them in the CLI. +Explicit `-i` paths can be in any order and are matched by hash. All sources +are verified before the first pipeline step. With `--project`, configuration, +rotation, offset and finger flags cannot silently override the recipe; only +`-i`, `-o`, `--save-project` and `--lang` may be added. +The `--save-project` destination must differ from every STL input and the STL +output; overwriting the opened JSON recipe itself is allowed. + +A figure's `offset` is its individual addition to `config.offset_x/y/z` and is +applied exactly once. The web UI has no separate global-offset controls, so +its exports carry the effective per-figure offsets shown there and zero global +offsets. + +Version 1 is strict: malformed JSON, missing or unknown fields, invalid hashes +and unsupported versions fail with a readable error instead of a best-guess +import. The web importer also rejects values outside its existing widget +ranges or between their steps (for example fractional-degree rotations or grip +positions not divisible by 5 %) rather than silently rounding them. Such +projects remain usable in the CLI when their `Config` is valid. A custom box +must specify all dimensions for its shape in the web app; partially automatic +dimensions remain a CLI feature. An automatic figure gap keeps following the +wall thickness after export and reopening. Reopening a +project preserves the computed geometry and wall findings within normal +floating-point tolerances; STL byte-for-byte equality is not required. + --- ## 🧪 Tests @@ -528,7 +585,7 @@ value as a usage error before any work starts. - **Language and threads:** the selected language lives in a `ContextVar`, not a module global, so two Streamlit sessions cannot overwrite each other's choice. `ThreadPoolExecutor` workers start with a fresh context and do *not* inherit it — `_parallel_map` therefore captures the language and re-applies it inside each worker, otherwise parallel steps would log in the default language. - **Measured, not predicted:** `build_inlay` solidifies every figure first and then arranges and dimensions the box from those real cavities. Voxelisation shifts a cavity by up to half a `voxel_pitch` depending on where it lies on the grid, so every box sized from a predicted allowance was off by that much: side walls came out 1.75–2.4 mm and floors 2.2–2.6 mm for a 2 mm target, and the wall between two cavities `figure_gap − voxel_pitch`. Now side and floor walls are `wall_thickness` and the wall between cavities is `figure_gap` — the invariant tests measure exactly that. At identical settings boxes can therefore come out slightly smaller or larger than before. - **Box height:** every figure sinks `depth_fraction` of its own height below the top face, wherever its STL sits in Z. The floor is `wall_thickness` under the deepest cavity; shorter figures sit on a thicker floor. Previously all figures were aligned at their tops against the tallest one — a short figure next to a tall one got no pocket at all, and two figures at different Z origins produced a solid block. -- **Rotation and layout:** the layout uses the rotated figures, so rotated cavities never overlap; the web app uses the unrotated figures only to keep the *order* stable while you rotate. Previously the slots came from the unrotated figures and a rotation could merge two cavities. +- **Rotation and layout:** the layout uses the rotated figures, so rotated cavities never overlap; the web app and CLI use the unrotated figures only to keep the *order* stable while you rotate. Both entry points therefore arrange the same recipe identically. Previously the slots came from the unrotated figures and a rotation could merge two cavities. - **Manual offsets** move a figure inside a box that stays put; walls made too thin that way are reported by the check. - **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. diff --git a/app.py b/app.py index af56714..6bffc84 100644 --- a/app.py +++ b/app.py @@ -20,6 +20,8 @@ import time import tempfile import threading +import uuid +from dataclasses import replace import plotly.graph_objects as go import streamlit as st @@ -29,6 +31,7 @@ import app_helpers import i18n import inlayer +import inlayer_project from i18n import t # --- Sprache ---------------------------------------------------------------- @@ -210,28 +213,88 @@ def log(self, msg, t0=None): uploaded_files = st.sidebar.file_uploader( t("app.upload.label"), type=["stl"], accept_multiple_files=True, key="uploads", ) or [] -multi_mode = len(uploaded_files) > 1 -if multi_mode: - st.sidebar.info(t("app.upload.multi_info", n=len(uploaded_files))) +project_upload = st.sidebar.file_uploader( + t("app.project.upload.label"), type=["json"], accept_multiple_files=False, + key="project_upload", help=t("app.project.upload.help"), +) -# Content hash per upload, computed once per upload rather than on every rerun. -# It is the identity of a file in every process-wide cache key and in the -# staleness snapshot - name and size are not (see _preview_mesh). +# Content hashes per upload, computed once rather than on every rerun. The +# short digest keys process-wide caches; the full SHA-256 is the persistent +# source identity in project files. Neither uses a file name as identity. _known_hashes = st.session_state.get("_hash_by_file_id", {}) content_hashes = { uf.file_id: _known_hashes.get(uf.file_id) or app_helpers.bytes_hash(uf.getvalue()) for uf in uploaded_files } st.session_state["_hash_by_file_id"] = content_hashes +_known_project_hashes = st.session_state.get("_project_hash_by_file_id", {}) +project_hashes = { + uf.file_id: _known_project_hashes.get(uf.file_id) + or inlayer_project.bytes_hash(uf.getvalue()) + for uf in uploaded_files +} +st.session_state["_project_hash_by_file_id"] = project_hashes + +project_error = None +project_notice = None +if project_upload is not None: + recipe_bytes = project_upload.getvalue() + import_signature = ( + inlayer_project.bytes_hash(recipe_bytes), + tuple((uf.file_id, project_hashes[uf.file_id]) for uf in uploaded_files), + ) + try: + recipe = inlayer_project.loads_project(recipe_bytes) + if len(uploaded_files) > app_helpers.MAX_UPLOAD_FILES: + raise inlayer_project.ProjectError(t( + "app.error.too_many_files", n=len(uploaded_files), + limit=app_helpers.MAX_UPLOAD_FILES, + )) + candidates = [ + inlayer_project.SourceCandidate(uf.name, project_hashes[uf.file_id]) + for uf in uploaded_files + ] + matches = inlayer_project.match_project_sources(recipe, candidates) + uploaded_files = [uploaded_files[match.candidate_index] for match in matches] + if st.session_state.get("_project_import_signature") != import_signature: + values, imported_stored = app_helpers.project_session_state( + recipe, [uf.file_id for uf in uploaded_files] + ) + st.session_state.update(values) + st.session_state["fig_offsets_dict"] = imported_stored + st.session_state["_project_id_by_file_id"] = { + uf.file_id: match.figure.id for match, uf in zip(matches, uploaded_files) + } + st.session_state["_project_import_signature"] = import_signature + project_notice = t("app.project.imported", n=len(uploaded_files)) + except inlayer_project.ProjectError as error: + project_error = str(error) + st.sidebar.error(project_error) +else: + st.session_state.pop("_project_import_signature", None) + +multi_mode = len(uploaded_files) > 1 +if multi_mode: + st.sidebar.info(t("app.upload.multi_info", n=len(uploaded_files))) +if project_notice is not None: + st.sidebar.success(project_notice) # 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 = None +fallback_full_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) + stat = os.stat(fallback_path) + cache_key = (fallback_hash, stat.st_mtime_ns, stat.st_size) + cached = st.session_state.get("_fallback_project_hash") + if cached is None or cached[0] != cache_key: + cached = (cache_key, inlayer_project.file_hash(fallback_path)) + st.session_state["_fallback_project_hash"] = cached + fallback_full_hash = cached[1] except OSError as error: # An unavailable input marks old results stale; Generate reports why. fallback_read_error = error @@ -687,6 +750,84 @@ def _axis_row(axis: str, label: str, lo: float, hi: float, step: float, hint: st ) +def _current_config() -> inlayer.Config: + """The one configuration used by both the run and the project export.""" + return inlayer.Config( + clearance=clearance, + wall_thickness=wall_thickness, + depth_fraction=depth_fraction, + voxel_pitch=voxel_pitch, + decimate_faces=decimate_faces, + stl_unit_to_mm=scale, + box_shape=box_shape, + box_width=box_width, + box_depth=box_depth, + box_height=box_height, + box_diameter=box_diameter, + figure_gap=figure_gap, + layout_style=layout_style, + enable_finger_recesses=enable_finger_recesses, + finger_radius=finger_radius, + finger_recess_axis=finger_recess_axis, + finger_recess_z_offset=finger_recess_z_offset, + enable_parallel=enable_parallel, + ) + + +def _project_config() -> inlayer.Config: + """Keep hidden multi-figure choices without changing what a run uses.""" + config = _current_config() + return replace( + config, + figure_gap=float(st.session_state["figure_gap"]) + if st.session_state.get("_gap_user_set") else None, + layout_style=st.session_state.get("layout_style", config.layout_style), + ) + + +def _project_json() -> str | None: + """Serialize current inputs without ever embedding their STL bytes.""" + sources = [] + if uploaded_files: + project_ids = st.session_state.setdefault("_project_id_by_file_id", {}) + for gone in set(project_ids) - set(fig_ids): + del project_ids[gone] + for file_id in fig_ids: + project_ids.setdefault(file_id, str(uuid.uuid4())) + figure_ids = [project_ids[file_id] for file_id in fig_ids] + sources = [ + inlayer_project.SourceIdentity(uf.name, project_hashes[uf.file_id]) + for uf in uploaded_files + ] + elif fallback_full_hash is not None: + figure_ids = [st.session_state.setdefault("_fallback_project_id", str(uuid.uuid4()))] + sources = [inlayer_project.SourceIdentity(fallback_path, fallback_full_hash)] + else: + return None + recipe = inlayer_project.new_project( + _project_config(), sources, + rotations=[values["rotation"] for values in applied], + offsets=[values["offset"] for values in applied], + recess_positions=[values["recess_position"] for values in applied], + figure_ids=figure_ids, + ) + return inlayer_project.dumps_project(recipe) + + +project_json = _project_json() if project_error is None else None +if project_json is None: + st.session_state.pop("_project_export", None) +else: + st.session_state["_project_export"] = project_json + st.sidebar.markdown("---") + st.sidebar.markdown(t("app.project.heading")) + st.sidebar.download_button( + label=t("app.project.download"), data=project_json, + file_name="inlay-project.json", mime="application/json", + help=t("app.project.download.help"), key="project_download", + ) + + def _params_snapshot() -> dict: """Everything a result depends on, for the "settings changed" check. @@ -730,6 +871,9 @@ def _params_snapshot() -> dict: # --- Pipeline --------------------------------------------------------------- if run_btn: st.session_state.pop("result", None) + if project_error is not None: + st.error(project_error) + st.stop() tmp_paths: list[str] = [] try: # Input: the uploads, or the default file next to the app @@ -765,26 +909,7 @@ def _params_snapshot() -> dict: logger = StreamlitLogger(status_box) t_start = time.perf_counter() - config = inlayer.Config( - clearance=clearance, - wall_thickness=wall_thickness, - depth_fraction=depth_fraction, - voxel_pitch=voxel_pitch, - decimate_faces=decimate_faces, - stl_unit_to_mm=scale, - box_shape=box_shape, - box_width=box_width, - box_depth=box_depth, - box_height=box_height, - box_diameter=box_diameter, - figure_gap=figure_gap, - layout_style=layout_style, - enable_finger_recesses=enable_finger_recesses, - finger_radius=finger_radius, - finger_recess_axis=finger_recess_axis, - finger_recess_z_offset=finger_recess_z_offset, - enable_parallel=enable_parallel, - ) + config = _current_config() progress = st.progress(0, text=t("app.progress.start")) rotations = [a["rotation"] for a in applied] diff --git a/app_helpers.py b/app_helpers.py index 8c5f6ae..2453842 100644 --- a/app_helpers.py +++ b/app_helpers.py @@ -27,11 +27,13 @@ import hashlib import io +import math import trimesh import inlayer +import inlayer_project from i18n import t # Chunk-Groesse beim Hashen; haelt den Speicherbedarf bei grossen STLs konstant. @@ -129,6 +131,123 @@ def applied_figure_params( return applied +def project_session_state( + recipe: inlayer_project.Project, figure_ids: list[str] +) -> tuple[dict[str, object], dict[str, dict[str, float]]]: + """Session values for a recipe, rejecting values the widgets would alter. + + Upload ids are only the targets of this one-time mapping. The recipe's own + persistent ids stay in the project and are never derived from Streamlit. + """ + if len(figure_ids) != len(recipe.figures): + raise inlayer_project.ProjectError(t("project.invalid_field", field="figures")) + + def unsupported(field: str): + raise inlayer_project.ProjectError(t("project.web_value", field=field)) + + def ranged(field: str, value: float, lo: float, hi: float) -> float: + if not lo <= value <= hi: + unsupported(field) + return value + + def slider(field: str, value: float, lo: float, hi: float, step: float) -> float: + ranged(field, value, lo, hi) + steps = (value - lo) / step + if not math.isclose(steps, round(steps), abs_tol=1e-8): + unsupported(field) + return round(lo + round(steps) * step, 10) + + def integer(field: str, value: float, lo: float, hi: float) -> float: + ranged(field, value, lo, hi) + if not math.isclose(value, round(value), abs_tol=1e-8): + unsupported(field) + return float(round(value)) + + config = recipe.config + box_fields = ("box_diameter", "box_height") if config.box_shape == "cylinder" else ( + "box_width", "box_depth", "box_height", + ) + use_custom_box = any(getattr(config, field) is not None for field in box_fields) + if use_custom_box: + for field in box_fields: + if getattr(config, field) is None: + unsupported(field) + gap = config.wall_thickness if config.figure_gap is None else slider( + "figure_gap", config.figure_gap, 0.5, 40.0, 0.5 + ) + values: dict[str, object] = { + "clearance": slider("clearance", config.clearance, 0.1, 2.0, 0.1), + "wall_thickness": slider("wall_thickness", config.wall_thickness, 1.0, 5.0, 0.5), + "depth_fraction": slider("depth_fraction", config.depth_fraction, 0.3, 1.0, 0.05), + "voxel_pitch": slider("voxel_pitch", config.voxel_pitch, 0.2, 1.0, 0.1), + "decimate_faces": ranged("decimate_faces", config.decimate_faces, 5000, 50000), + "scale": ranged("stl_unit_to_mm", config.stl_unit_to_mm, 0.01, 100.0), + "finger_enabled": config.enable_finger_recesses, + "finger_axis": config.finger_recess_axis, + "_w_finger_axis": config.finger_recess_axis, + "parallel": config.enable_parallel, + "box_shape": config.box_shape, + "_w_box_shape": config.box_shape, + "use_custom_box": use_custom_box, + "manual_offsets": any( + not math.isclose(value, 0.0, abs_tol=1e-12) + for offset in inlayer_project.effective_offsets(recipe) for value in offset + ), + "manual_rotations": any( + not math.isclose(value % 360.0, 0.0, abs_tol=1e-12) + for figure in recipe.figures for value in figure.rotation + ), + "pos_step": 1.0, + "rot_step": 1.0, + "_w_pos_step": 1.0, + "_w_rot_step": 1.0, + "layout_style": config.layout_style, + "_w_layout_style": config.layout_style, + "figure_gap": gap, + "_sl_figure_gap": gap, + "_ni_figure_gap": gap, + "_gap_user_set": config.figure_gap is not None, + } + for key, field, value, lo, hi in ( + ("finger_radius", "finger_radius", config.finger_radius, 5.0, 15.0), + ("finger_z_offset", "finger_recess_z_offset", config.finger_recess_z_offset, 0.0, 30.0), + ): + step = 0.5 + values[key] = slider(field, value, lo, hi, step) + values[f"_{key}_value"] = values[key] + for key, field, value, default, lo, hi in ( + ("box_width", "box_width", config.box_width, 50.0, 10.0, 300.0), + ("box_depth", "box_depth", config.box_depth, 50.0, 10.0, 300.0), + ("box_height", "box_height", config.box_height, 20.0, 5.0, 200.0), + ("box_diameter", "box_diameter", config.box_diameter, 50.0, 10.0, 300.0), + ): + checked = default if value is None else ranged(field, value, lo, hi) + values[key] = checked + values[f"_{key}_value"] = checked + + stored = {} + effective = inlayer_project.effective_offsets(recipe) + for figure, upload_id, offset in zip(recipe.figures, figure_ids, effective): + rotation = [integer(f"rotation[{i}]", value % 360.0, 0.0, 359.0) + for i, value in enumerate(figure.rotation)] + offset = [ + integer(f"offset_{axis}", value, limits[0], limits[1]) + for axis, value, limits in zip("xyz", offset, ((-100, 100), (-100, 100), (-50, 150))) + ] + percent = figure.finger_recess_position * 100.0 + if not math.isclose(percent / 5.0, round(percent / 5.0), rel_tol=0.0, abs_tol=1e-8): + unsupported("finger_recess_position") + stored[upload_id] = { + **dict(FIGURE_DEFAULTS), + **dict(zip(OFFSET_AXES, offset)), + **dict(zip(ROTATION_AXES, rotation)), + "finger_recess_position": round(percent) / 100.0, + } + for selection in ("selected_recess_fig", "selected_fig", "selected_rot_fig"): + values[f"_ref_{selection}"] = None + return values, stored + + def is_rotation_axis(axis: str) -> bool: """True fuer Rotationsachsen (rot_x/rot_y/rot_z), sonst False.""" return axis.startswith("rot_") diff --git a/i18n.py b/i18n.py index ccd0980..736a1d5 100644 --- a/i18n.py +++ b/i18n.py @@ -147,6 +147,30 @@ def t(key: str, /, **kwargs: object) -> str: "de": "📂 {n} Figuren geladen – automatische Anordnung aktiv", "en": "📂 {n} figures loaded – automatic arrangement active", }, + "app.project.upload.label": { + "de": "Projekt öffnen (JSON, optional)", + "en": "Open project (JSON, optional)", + }, + "app.project.upload.help": { + "de": "Formatversion 1. Lade zusätzlich alle ursprünglichen STLs hoch. Ihre SHA-256-Hashes müssen übereinstimmen; die Dateinamen und ihre Reihenfolge sind unwichtig. STLs sind nicht im JSON eingebettet.", + "en": "Format version 1. Also upload all original STLs. Their SHA-256 hashes must match; file names and order do not matter. STLs are not embedded in the JSON.", + }, + "app.project.imported": { + "de": "Projekt geladen: {n} Figuren und ihre Quellen wurden per SHA-256 geprüft.", + "en": "Project loaded: {n} figures and their sources were verified by SHA-256.", + }, + "app.project.heading": { + "de": "### 💾 Projekt", + "en": "### 💾 Project", + }, + "app.project.download": { + "de": "Projekt als JSON speichern", + "en": "Download project as JSON", + }, + "app.project.download.help": { + "de": "Speichert Formatversion 1 mit Konfiguration, vollständigen SHA-256-Quellhashes, stabilen Figuren-IDs sowie individuellen Rotationen, Offsets und Griffpositionen. Deaktivierte individuelle Funktionen werden mit ihren wirksamen Nullwerten gespeichert. STLs werden nicht eingebettet.", + "en": "Saves format version 1 with configuration, full SHA-256 source hashes, stable figure ids and individual rotations, offsets and grip positions. Disabled individual features are saved with their effective zero values. STLs are not embedded.", + }, # --- Sidebar: Druckeinstellungen --------------------------------------- "app.printer.heading": { "de": "### 📐 FDM-Drucker Einstellungen", @@ -829,6 +853,55 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Die Figur", "en": "The figure", }, + # --- Versionierte Projektdateien ----------------------------------------- + "project.invalid_json": { + "de": "Die Projektdatei ist kein gültiges UTF-8-JSON.", + "en": "The project file is not valid UTF-8 JSON.", + }, + "project.too_large": { + "de": "Die Projektdatei ist größer als die erlaubten {limit} Bytes.", + "en": "The project file exceeds the allowed {limit} bytes.", + }, + "project.invalid_field": { + "de": "Ungültiges oder unbekanntes Feld im Projekt: {field}", + "en": "Invalid or unknown field in the project: {field}", + }, + "project.missing_field": { + "de": "Pflichtfeld im Projekt fehlt: {field}", + "en": "Required project field is missing: {field}", + }, + "project.unsupported_format": { + "de": "Die Datei ist kein Inlayer-Projekt (Format: {value}).", + "en": "The file is not an Inlayer project (format: {value}).", + }, + "project.unsupported_version": { + "de": "Projektversion {version} wird nicht unterstützt; diese Version liest ausschließlich Formatversion 1.", + "en": "Project version {version} is not supported; this version only reads format version 1.", + }, + "project.duplicate_id": { + "de": "Die Projektdatei enthält eine Figuren-ID mehrfach.", + "en": "The project file contains a duplicate figure id.", + }, + "project.source_not_provided": { + "de": "Für '{name}' fehlt eine Quelldatei mit dem erwarteten SHA-256-Hash {hash}… . Die Datei wurde möglicherweise verändert oder nicht hochgeladen.", + "en": "No source file for '{name}' has the expected SHA-256 hash {hash}… . It may have changed or was not uploaded.", + }, + "project.source_unmatched": { + "de": "Die Quelldatei '{name}' gehört nicht zum Projekt oder ihr Inhalt wurde verändert.", + "en": "Source file '{name}' does not belong to the project or its content has changed.", + }, + "project.source_missing": { + "de": "Quelldatei für '{name}' wurde nicht gefunden: {path}", + "en": "Source file for '{name}' was not found: {path}", + }, + "project.source_changed": { + "de": "Quelldatei für '{name}' wurde seit dem Export verändert: {path}", + "en": "Source file for '{name}' has changed since the project was exported: {path}", + }, + "project.web_value": { + "de": "Der Wert von '{field}' kann in der Weboberfläche nicht verlustfrei dargestellt werden. Das Projekt wurde nicht verändert; nutze die CLI oder passe das Rezept an.", + "en": "The value of '{field}' cannot be represented losslessly in the web app. The project was not changed; use the CLI or adjust the recipe.", + }, # --- CLI ---------------------------------------------------------------- "cli.description": { "de": "Inlayer: Erstellt 3D-druckbare Verpackungseinleger für Figuren.", @@ -846,6 +919,34 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Pfad zur Ausgabe-STL-Datei (Standard: '{default}')", "en": "Path to the output STL file (default: '{default}')", }, + "cli.project": { + "de": "Inlayer-Projekt (JSON, Formatversion {version}) öffnen; ohne -i werden die gespeicherten Quellpfade verwendet", + "en": "Open an Inlayer project (JSON, format version {version}); without -i its stored source paths are used", + }, + "cli.save_project": { + "de": "Konfiguration, Figurenidentitäten und individuelle Einstellungen als versioniertes JSON-Projekt speichern", + "en": "Save configuration, figure identities and individual settings as a versioned JSON project", + }, + "cli.project_loaded": { + "de": "Projekt {path} geladen und alle {n} Quelldateien per SHA-256 geprüft", + "en": "Loaded project {path} and verified all {n} source files by SHA-256", + }, + "cli.project_saved": { + "de": " => Projekt {path} gespeichert", + "en": " => saved project {path}", + }, + "cli.error.project_override": { + "de": "{option} kann nicht mit --project kombiniert werden: Die Einstellungen kommen aus dem Projekt. Erlaubt sind -i, -o, --save-project und --lang.", + "en": "{option} cannot be combined with --project: settings come from the project. Only -i, -o, --save-project and --lang are allowed.", + }, + "cli.error.project_path_conflict": { + "de": "Projektziel {path!r} kollidiert mit Eingabe- oder STL-Ausgabedatei {other!r}.", + "en": "Project destination {path!r} conflicts with input or STL output {other!r}.", + }, + "project.read_failed": { + "de": "Projektdatei {path} kann nicht gelesen werden: {error}", + "en": "Cannot read project file {path}: {error}", + }, "cli.clearance": { "de": "Spiel zwischen Figur und Aussparung in mm (Standard: {default})", "en": "Clearance between figure and cavity in mm (default: {default})", diff --git a/inlayer.py b/inlayer.py index e3c0fc2..cc2ef58 100644 --- a/inlayer.py +++ b/inlayer.py @@ -1153,13 +1153,21 @@ def _build_parser() -> argparse.ArgumentParser: default=i18n.get_language(), env=i18n.ENV_VAR), ) parser.add_argument( - "-i", "--input", nargs="+", default=[DEFAULT_INPUT], + "-i", "--input", nargs="+", default=None, help=t_("cli.input") ) parser.add_argument( "-o", "--output", default="inlay.stl", help=t_("cli.output", default="inlay.stl") ) + parser.add_argument( + "--project", default=None, + help=t_("cli.project", version=1) + ) + parser.add_argument( + "--save-project", default=None, + help=t_("cli.save_project") + ) parser.add_argument( "-c", "--clearance", type=float, default=Config.clearance, help=t_("cli.clearance", default=Config.clearance) @@ -1278,79 +1286,171 @@ def main(argv: list[str] | None = None) -> int: # evaluates the help texts while the arguments are added, a --lang parsed # later would come too late for them. So the option is fished out of argv # up front; without it INLAYER_LANG decides. + raw_argv = list(sys.argv[1:] if argv is None else argv) pre = argparse.ArgumentParser(add_help=False) pre.add_argument("--lang", choices=sorted(i18n.LANGUAGES)) - pre_args, _ = pre.parse_known_args(argv) + pre_args, _ = pre.parse_known_args(raw_argv) i18n.set_language(pre_args.lang or i18n.language_from_env()) parser = _build_parser() - args = parser.parse_args(argv) - input_paths = args.input - - # Everything that can be rejected is rejected here, before minutes of - # voxel work: argparse then prints a usage error instead of a traceback. - for path in input_paths: - if not os.path.isfile(path): - parser.error(t_("error.input_not_found", path=path)) - # The inlay is written after all the work is done - a typo in the output - # directory used to cost the whole run. - out_dir = os.path.dirname(os.path.abspath(args.output)) - if ( - not args.output - or args.output.endswith((os.sep, os.altsep or os.sep)) - or os.path.isdir(args.output) - or not os.path.isdir(out_dir) - or not os.access(args.output if os.path.exists(args.output) else out_dir, os.W_OK) - ): - parser.error(t_("cli.error.output_not_writable", path=args.output)) - # The rotations are the only numbers that do not pass through Config and - # its checks: --rot-x nan ran the whole pipeline on a mesh of NaNs and - # wrote a solid block. - for name in ("rot_x", "rot_y", "rot_z"): - if not math.isfinite(getattr(args, name)): - parser.error(t_("config.must_be_finite", name=name, value=getattr(args, name))) - # One recess position applies to every figure, otherwise one per input - # file - only checked when recesses are on, the flag does nothing else. - recess_positions = args.finger_recess_position or [Config.finger_recess_position] - for value in recess_positions: - if not -1.0 <= value <= 1.0: - parser.error(t_("config.bad_finger_position", value=value)) - if len(recess_positions) == 1: - recess_positions = recess_positions * len(input_paths) - elif args.finger_recesses and len(recess_positions) != len(input_paths): - parser.error( - t_("cli.error.recess_position_count", - given=len(recess_positions), n=len(input_paths)) - ) - if args.finger_recess_position is not None and not args.finger_recesses: - # Whatever was passed - the note used to appear for a wrong count only - print(t_("cli.recess_position_ignored")) - try: - config = Config( - clearance=args.clearance, - wall_thickness=args.wall_thickness, - depth_fraction=args.depth_fraction, - voxel_pitch=args.voxel_pitch, - decimate_faces=args.decimate_faces, - stl_unit_to_mm=args.scale, - box_shape=args.box_shape, - box_width=args.box_width, - box_depth=args.box_depth, - box_height=args.box_height, - box_diameter=args.box_diameter, - offset_x=args.offset_x, - offset_y=args.offset_y, - offset_z=args.offset_z, - figure_gap=args.figure_gap, - layout_style=args.layout_style, - enable_finger_recesses=args.finger_recesses, - finger_radius=args.finger_radius, - finger_recess_axis=args.finger_recess_axis, - finger_recess_z_offset=args.finger_recess_z_offset, - enable_parallel=args.parallel, - ) - except ValueError as exc: - parser.error(str(exc)) + # A supplied value can equal its default, and argparse accepts attached + # short values and long-option abbreviations. Track the parsed actions. + omitted = object() + config_actions = [ + action for action in parser._actions + if action.dest not in {"help", "input", "output", "project", "save_project", "lang"} + ] + args = parser.parse_args( + raw_argv, + namespace=argparse.Namespace(**{action.dest: omitted for action in config_actions}), + ) + supplied_config = [] + for action in config_actions: + if getattr(args, action.dest) is omitted: + setattr(args, action.dest, action.default) + else: + supplied_config.append(action) + import inlayer_project as project_io + + if args.project: + if supplied_config: + parser.error(t_( + "cli.error.project_override", option=supplied_config[0].option_strings[-1], + )) + try: + project = project_io.load_project(args.project) + except project_io.ProjectError as exc: + parser.error(str(exc)) + except OSError as exc: + parser.error(t_("project.read_failed", path=args.project, error=exc)) + try: + resolved_sources = project_io.resolve_project_paths( + project, args.input, project_path=args.project + ) + except (project_io.ProjectError, OSError) as exc: + parser.error(str(exc)) + input_paths = [source.path for source in resolved_sources] + file_names = [source.figure.source.name for source in resolved_sources] + config = project.config + rotations = [source.figure.rotation for source in resolved_sources] + individual_offsets = project_io.effective_offsets(project) + recess_positions = [source.figure.finger_recess_position for source in resolved_sources] + print(t_("cli.project_loaded", path=args.project, n=len(input_paths))) + else: + project = None + resolved_sources = None + input_paths = args.input or [DEFAULT_INPUT] + file_names = input_paths + for path in input_paths: + if not os.path.isfile(path): + parser.error(t_("error.input_not_found", path=path)) + for name in ("rot_x", "rot_y", "rot_z"): + if not math.isfinite(getattr(args, name)): + parser.error(t_("config.must_be_finite", name=name, value=getattr(args, name))) + rotations = [(args.rot_x, args.rot_y, args.rot_z)] * len(input_paths) + individual_offsets = None + recess_positions = args.finger_recess_position or [Config.finger_recess_position] + for value in recess_positions: + if not -1.0 <= value <= 1.0: + parser.error(t_("config.bad_finger_position", value=value)) + if len(recess_positions) == 1: + recess_positions = recess_positions * len(input_paths) + elif args.finger_recesses and len(recess_positions) != len(input_paths): + parser.error(t_( + "cli.error.recess_position_count", + given=len(recess_positions), n=len(input_paths), + )) + if args.finger_recess_position is not None and not args.finger_recesses: + print(t_("cli.recess_position_ignored")) + try: + config = Config( + clearance=args.clearance, + wall_thickness=args.wall_thickness, + depth_fraction=args.depth_fraction, + voxel_pitch=args.voxel_pitch, + decimate_faces=args.decimate_faces, + stl_unit_to_mm=args.scale, + box_shape=args.box_shape, + box_width=args.box_width, + box_depth=args.box_depth, + box_height=args.box_height, + box_diameter=args.box_diameter, + offset_x=args.offset_x, + offset_y=args.offset_y, + offset_z=args.offset_z, + figure_gap=args.figure_gap, + layout_style=args.layout_style, + enable_finger_recesses=args.finger_recesses, + finger_radius=args.finger_radius, + finger_recess_axis=args.finger_recess_axis, + finger_recess_z_offset=args.finger_recess_z_offset, + enable_parallel=args.parallel, + ) + except ValueError as exc: + parser.error(str(exc)) + + # Reject unwritable destinations before hashing or any voxel work. + for output_path in (args.output, args.save_project): + if output_path is None: + continue + out_dir = os.path.dirname(os.path.abspath(output_path)) + if ( + not output_path + or output_path.endswith((os.sep, os.altsep or os.sep)) + or os.path.isdir(output_path) + or not os.path.isdir(out_dir) + or not os.access(output_path if os.path.exists(output_path) else out_dir, os.W_OK) + ): + parser.error(t_("cli.error.output_not_writable", path=output_path)) + + if args.save_project: + for other_path in [*input_paths, args.output]: + same_path = os.path.realpath(args.save_project) == os.path.realpath(other_path) + same_file = ( + os.path.exists(args.save_project) and os.path.exists(other_path) + and os.path.samefile(args.save_project, other_path) + ) + if same_path or same_file: + parser.error(t_( + "cli.error.project_path_conflict", path=args.save_project, other=other_path, + )) + + project_to_save = None + if args.save_project: + try: + if project is None: + sources = [ + project_io.SourceIdentity( + os.path.basename(path), project_io.file_hash(path), path + ) + for path in input_paths + ] + export_rotations = rotations + export_offsets = [(0.0, 0.0, 0.0)] * len(input_paths) + export_positions = ( + recess_positions if config.enable_finger_recesses + else [config.finger_recess_position] * len(input_paths) + ) + export_ids = None + else: + assert resolved_sources is not None + sources = [ + project_io.SourceIdentity( + source.figure.source.name, source.figure.source.sha256, source.path + ) + for source in resolved_sources + ] + export_rotations = [figure.rotation for figure in project.figures] + export_offsets = [figure.offset for figure in project.figures] + export_positions = [figure.finger_recess_position for figure in project.figures] + export_ids = [figure.id for figure in project.figures] + project_to_save = project_io.new_project( + config, sources, rotations=export_rotations, offsets=export_offsets, + recess_positions=export_positions, figure_ids=export_ids, + project_path=args.save_project, + ) + except (project_io.ProjectError, OSError) as exc: + parser.error(str(exc)) multi = len(input_paths) > 1 t_total = time.perf_counter() @@ -1366,23 +1466,28 @@ def main(argv: list[str] | None = None) -> int: what=t_("pipeline.what.prepare"), ) rotated = [ - apply_euler_rotation(m, args.rot_x, args.rot_y, args.rot_z) for m in prepared + apply_euler_rotation(mesh, *rotation) + for mesh, rotation in zip(prepared, rotations) ] # Step 2: tolerance offset per figure (optionally in parallel) print(t_("cli.step2")) dilated_meshes = _parallel_map( lambda item: dilate(item[0], config.clearance, config, name=item[1]), - zip(rotated, input_paths), config, what=t_("pipeline.what.dilate"), + zip(rotated, file_names), config, what=t_("pipeline.what.dilate"), ) # Step 3: arrange, cut and check (build_inlay does all three) print(t_("cli.step3")) inlay, box_w, box_d, box_h = build_inlay( - dilated_meshes, config, file_names=input_paths, + dilated_meshes, config, file_names=file_names, + individual_offsets=individual_offsets, individual_recess_positions=recess_positions if config.enable_finger_recesses else None, + sorting_reference=prepared, ) inlay.export(file_obj=args.output, file_type="stl") + if project_to_save is not None: + project_io.save_project(project_to_save, args.save_project) except (ValueError, RuntimeError, OSError, MemoryError) as exc: # What the pipeline raises on purpose names the file and the remedy. # A traceback on top of it buried that one line; anything else is a @@ -1391,6 +1496,8 @@ def main(argv: list[str] | None = None) -> int: print(t_("cli.error.failed", error=reason), file=sys.stderr) return EXIT_FAILED print(t_("cli.saved", path=args.output)) + if project_to_save is not None: + print(t_("cli.project_saved", path=args.save_project)) # Step 4: wall check print(t_("cli.step4")) diff --git a/inlayer_project.py b/inlayer_project.py new file mode 100644 index 0000000..045911f --- /dev/null +++ b/inlayer_project.py @@ -0,0 +1,416 @@ +# Inlayer - erzeugt 3D-druckbare Verpackungseinleger aus STL-Figuren. +# Copyright (C) 2026 Marco Wittwer, Mirko Wittwer +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License +# for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +"""Versioned, STL-free project recipes shared by the CLI and the web app.""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import uuid +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any, Final, Sequence + +from i18n import t +from inlayer import Config + +FORMAT_NAME: Final = "inlayer-project" +PROJECT_VERSION: Final = 1 +MAX_PROJECT_BYTES: Final = 2_000_000 +_HASH_CHUNK_BYTES: Final = 1024 * 1024 +_SHA256_RE: Final = re.compile(r"[0-9a-fA-F]{64}\Z") + + +class ProjectError(ValueError): + """A project cannot be parsed, validated or matched to its sources.""" + + +@dataclass(frozen=True) +class SourceIdentity: + name: str + sha256: str + path: str | None = None + + +@dataclass(frozen=True) +class ProjectFigure: + id: str + source: SourceIdentity + rotation: tuple[float, float, float] = (0.0, 0.0, 0.0) + offset: tuple[float, float, float] = (0.0, 0.0, 0.0) + finger_recess_position: float = 0.0 + + +@dataclass(frozen=True) +class Project: + config: Config + figures: tuple[ProjectFigure, ...] + version: int = PROJECT_VERSION + + +@dataclass(frozen=True) +class SourceCandidate: + name: str + sha256: str + path: str | None = None + + +@dataclass(frozen=True) +class SourceMatch: + figure: ProjectFigure + candidate_index: int + + +@dataclass(frozen=True) +class ResolvedSource: + figure: ProjectFigure + path: str + supplied_name: str + + +def bytes_hash(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def file_hash(path: str | os.PathLike[str]) -> str: + digest = hashlib.sha256() + with open(path, "rb") as source: + for chunk in iter(lambda: source.read(_HASH_CHUNK_BYTES), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _invalid(field: str) -> ProjectError: + return ProjectError(t("project.invalid_field", field=field)) + + +def _exact_keys(value: Any, expected: set[str], field: str) -> dict: + if not isinstance(value, dict): + raise _invalid(field) + missing = sorted(expected - set(value)) + if missing: + raise ProjectError(t("project.missing_field", field=f"{field}.{missing[0]}")) + unknown = sorted(set(value) - expected) + if unknown: + raise _invalid(f"{field}.{unknown[0]}") + return value + + +def _text(value: Any, field: str, *, allow_empty: bool = False) -> str: + if not isinstance(value, str) or (not allow_empty and not value.strip()) or "\x00" in value: + raise _invalid(field) + if len(value) > 4096: + raise _invalid(field) + try: + value.encode("utf-8") + except UnicodeEncodeError as exc: + raise _invalid(field) from exc + return value + + +def _number(value: Any, field: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise _invalid(field) + try: + converted = float(value) + except OverflowError as exc: + raise _invalid(field) from exc + if not math.isfinite(converted): + raise _invalid(field) + return converted + + +def _vector(value: Any, field: str) -> tuple[float, float, float]: + if not isinstance(value, list) or len(value) != 3: + raise _invalid(field) + x, y, z = (_number(component, f"{field}[{i}]") for i, component in enumerate(value)) + return x, y, z + + +def _hash(value: Any, field: str) -> str: + text = _text(value, field) + if _SHA256_RE.fullmatch(text) is None: + raise _invalid(field) + return text.lower() + + +def _config(raw: Any) -> Config: + definitions = fields(Config) + data = _exact_keys(raw, {field.name for field in definitions}, "config") + optional = {"box_width", "box_depth", "box_height", "box_diameter", "figure_gap"} + booleans = {"enable_finger_recesses", "enable_parallel"} + strings = {"box_shape", "layout_style", "finger_recess_axis"} + values: dict[str, Any] = {} + for field in definitions: + value = data[field.name] + if field.name in optional and value is None: + values[field.name] = None + elif field.name in booleans: + if not isinstance(value, bool): + raise _invalid(f"config.{field.name}") + values[field.name] = value + elif field.name == "decimate_faces": + if isinstance(value, bool) or not isinstance(value, int): + raise _invalid(f"config.{field.name}") + values[field.name] = value + elif field.name in strings: + values[field.name] = _text(value, f"config.{field.name}") + else: + values[field.name] = _number(value, f"config.{field.name}") + try: + return Config(**values) + except ValueError as exc: + raise ProjectError(str(exc)) from exc + + +def _figure(raw: Any, index: int) -> ProjectFigure: + label = f"figures[{index}]" + data = _exact_keys( + raw, {"id", "source", "rotation", "offset", "finger_recess_position"}, label + ) + figure_id = _text(data["id"], f"{label}.id") + if len(figure_id) > 128: + raise _invalid(f"{label}.id") + source_data = _exact_keys(data["source"], {"name", "sha256", "path"}, f"{label}.source") + source_path = source_data["path"] + if source_path is not None: + source_path = _text(source_path, f"{label}.source.path") + source = SourceIdentity( + name=_text(source_data["name"], f"{label}.source.name"), + sha256=_hash(source_data["sha256"], f"{label}.source.sha256"), + path=source_path, + ) + return ProjectFigure( + id=figure_id, + source=source, + rotation=_vector(data["rotation"], f"{label}.rotation"), + offset=_vector(data["offset"], f"{label}.offset"), + finger_recess_position=_number( + data["finger_recess_position"], f"{label}.finger_recess_position" + ), + ) + + +def project_from_dict(raw: Any) -> Project: + data = _exact_keys(raw, {"format", "version", "config", "figures"}, "project") + if data["format"] != FORMAT_NAME: + raise ProjectError(t("project.unsupported_format", value=data["format"])) + version = data["version"] + if isinstance(version, bool) or not isinstance(version, int): + raise _invalid("version") + if version != PROJECT_VERSION: + raise ProjectError(t("project.unsupported_version", version=version)) + if not isinstance(data["figures"], list) or not data["figures"]: + raise _invalid("figures") + figures = tuple(_figure(raw_figure, i) for i, raw_figure in enumerate(data["figures"])) + ids = [figure.id for figure in figures] + if len(set(ids)) != len(ids): + raise ProjectError(t("project.duplicate_id")) + for i, figure in enumerate(figures): + if not -1.0 <= figure.finger_recess_position <= 1.0: + raise ProjectError(t("config.bad_finger_position", value=figure.finger_recess_position)) + return Project(config=_config(data["config"]), figures=figures, version=version) + + +def loads_project(data: str | bytes) -> Project: + if isinstance(data, str): + text = data + else: + if len(data) > MAX_PROJECT_BYTES: + raise ProjectError(t("project.too_large", limit=MAX_PROJECT_BYTES)) + try: + text = data.decode("utf-8") + except UnicodeDecodeError as exc: + raise ProjectError(t("project.invalid_json")) from exc + try: + size = len(text.encode("utf-8")) + except UnicodeEncodeError as exc: + raise ProjectError(t("project.invalid_json")) from exc + if size > MAX_PROJECT_BYTES: + raise ProjectError(t("project.too_large", limit=MAX_PROJECT_BYTES)) + try: + raw = json.loads(text) + except (ValueError, RecursionError) as exc: + raise ProjectError(t("project.invalid_json")) from exc + return project_from_dict(raw) + + +def load_project(path: str | os.PathLike[str]) -> Project: + return loads_project(Path(path).read_bytes()) + + +def project_to_dict(project: Project) -> dict[str, Any]: + return { + "format": FORMAT_NAME, + "version": project.version, + "config": {field.name: getattr(project.config, field.name) for field in fields(Config)}, + "figures": [ + { + "id": figure.id, + "source": { + "name": figure.source.name, + "sha256": figure.source.sha256, + "path": figure.source.path, + }, + "rotation": list(figure.rotation), + "offset": list(figure.offset), + "finger_recess_position": figure.finger_recess_position, + } + for figure in project.figures + ], + } + + +def dumps_project(project: Project) -> str: + return json.dumps(project_to_dict(project), ensure_ascii=False, indent=2, allow_nan=False) + "\n" + + +def save_project(project: Project, path: str | os.PathLike[str]) -> None: + Path(path).write_text(dumps_project(project), encoding="utf-8") + + +def new_project( + config: Config, + sources: Sequence[SourceIdentity], + *, + rotations: Sequence[Sequence[float]] | None = None, + offsets: Sequence[Sequence[float]] | None = None, + recess_positions: Sequence[float] | None = None, + figure_ids: Sequence[str] | None = None, + project_path: str | os.PathLike[str] | None = None, +) -> Project: + count = len(sources) + if count == 0: + raise _invalid("figures") + if rotations is None: + rotations = [(0.0, 0.0, 0.0)] * count + if offsets is None: + offsets = [(0.0, 0.0, 0.0)] * count + if recess_positions is None: + recess_positions = [config.finger_recess_position] * count + if figure_ids is None: + figure_ids = [str(uuid.uuid4()) for _ in sources] + if not all(len(values) == count for values in (rotations, offsets, recess_positions, figure_ids)): + raise _invalid("figures") + + project_dir = None if project_path is None else os.path.dirname(os.path.abspath(project_path)) + figures = [] + for i, source in enumerate(sources): + path = source.path + if path is not None and project_dir is not None: + path = os.path.relpath(os.path.abspath(path), start=project_dir) + figure = ProjectFigure( + id=_text(figure_ids[i], f"figures[{i}].id"), + source=SourceIdentity( + name=_text(source.name, f"figures[{i}].source.name"), + sha256=_hash(source.sha256, f"figures[{i}].source.sha256"), + path=path, + ), + rotation=_vector(list(rotations[i]), f"figures[{i}].rotation"), + offset=_vector(list(offsets[i]), f"figures[{i}].offset"), + finger_recess_position=_number( + recess_positions[i], f"figures[{i}].finger_recess_position" + ), + ) + figures.append(figure) + project = Project(config=config, figures=tuple(figures)) + project_from_dict(project_to_dict(project)) + return project + + +def match_project_sources(project: Project, candidates: Sequence[SourceCandidate]) -> list[SourceMatch]: + """Matches by full content hash, never by a name or a transient upload id.""" + by_hash: dict[str, list[int]] = {} + for i, candidate in enumerate(candidates): + by_hash.setdefault(candidate.sha256.lower(), []).append(i) + used: set[int] = set() + matches = [] + for figure in project.figures: + available = [i for i in by_hash.get(figure.source.sha256, []) if i not in used] + if not available: + raise ProjectError(t( + "project.source_not_provided", name=figure.source.name, + hash=figure.source.sha256[:12], + )) + index = available[0] + used.add(index) + matches.append(SourceMatch(figure=figure, candidate_index=index)) + unmatched = [candidate for i, candidate in enumerate(candidates) if i not in used] + if unmatched: + raise ProjectError(t("project.source_unmatched", name=unmatched[0].name)) + return matches + + +def resolve_project_paths( + project: Project, + input_paths: Sequence[str] | None, + *, + project_path: str | os.PathLike[str], +) -> list[ResolvedSource]: + """Checks every source before the pipeline starts and returns project order.""" + if input_paths is None: + candidates = [] + project_dir = os.path.dirname(os.path.abspath(project_path)) + for figure in project.figures: + if figure.source.path is None: + raise ProjectError(t( + "project.source_not_provided", name=figure.source.name, + hash=figure.source.sha256[:12], + )) + path = figure.source.path + if not os.path.isabs(path): + path = os.path.join(project_dir, path) + path = os.path.normpath(path) + if not os.path.isfile(path): + raise ProjectError(t( + "project.source_missing", name=figure.source.name, path=path, + )) + actual_hash = file_hash(path) + if actual_hash != figure.source.sha256: + raise ProjectError(t( + "project.source_changed", name=figure.source.name, path=path, + )) + candidates.append(SourceCandidate(name=figure.source.name, sha256=actual_hash, path=path)) + else: + candidates = [] + for supplied in input_paths: + if not os.path.isfile(supplied): + raise ProjectError(t("error.input_not_found", path=supplied)) + candidates.append(SourceCandidate( + name=os.path.basename(supplied), sha256=file_hash(supplied), path=supplied, + )) + matches = match_project_sources(project, candidates) + return [ + ResolvedSource( + figure=match.figure, + path=candidates[match.candidate_index].path or "", + supplied_name=candidates[match.candidate_index].name, + ) + for match in matches + ] + + +def effective_offsets(project: Project) -> list[tuple[float, float, float]]: + config = project.config + return [ + (config.offset_x + figure.offset[0], config.offset_y + figure.offset[1], + config.offset_z + figure.offset[2]) + for figure in project.figures + ] diff --git a/tests/test_app_helpers.py b/tests/test_app_helpers.py index 204d549..59321c7 100644 --- a/tests/test_app_helpers.py +++ b/tests/test_app_helpers.py @@ -8,6 +8,7 @@ from __future__ import annotations import hashlib +from dataclasses import replace from typing import cast import numpy as np @@ -15,6 +16,8 @@ import trimesh import app_helpers +import inlayer +import inlayer_project from tests.conftest import binary_stl @@ -81,6 +84,106 @@ def test_unknown_figure_gets_the_defaults(self): assert x["offset"] == (0.0, 0.0, 0.0) and x["recess_position"] == 0.0 +class TestProjectSessionState: + @staticmethod + def _recipe(): + config = inlayer.Config( + voxel_pitch=1.0, decimate_faces=5000, enable_finger_recesses=True, + ) + sources = [ + inlayer_project.SourceIdentity("model.stl", inlayer_project.bytes_hash(data)) + for data in (b"first", b"second") + ] + return inlayer_project.new_project( + config, sources, + rotations=[(370.0, 45.0, 0.0), (0.0, 0.0, 90.0)], + offsets=[(1.0, 2.0, 3.0), (-1.0, 0.0, 4.0)], + recess_positions=[0.25, -0.5], figure_ids=["persistent-one", "persistent-two"], + ) + + def test_same_named_sources_map_to_upload_ids_only_once(self): + values, stored = app_helpers.project_session_state( + self._recipe(), ["temporary-upload-b", "temporary-upload-a"] + ) + assert set(stored) == {"temporary-upload-a", "temporary-upload-b"} + assert not {"persistent-one", "persistent-two"} & set(stored) + first = stored["temporary-upload-b"] + second = stored["temporary-upload-a"] + assert (first["rot_x"], first["rot_y"], first["rot_z"]) == (10.0, 45.0, 0.0) + assert (second["rot_x"], second["rot_y"], second["rot_z"]) == (0.0, 0.0, 90.0) + assert (first["offset_x"], first["offset_y"], first["offset_z"]) == (1.0, 2.0, 3.0) + assert (second["offset_x"], second["offset_y"], second["offset_z"]) == (-1.0, 0.0, 4.0) + assert first["finger_recess_position"] == 0.25 + assert second["finger_recess_position"] == -0.5 + assert values["manual_offsets"] is True + assert values["manual_rotations"] is True + assert values["figure_gap"] == values["_sl_figure_gap"] == 2.0 + + def test_global_and_individual_offsets_are_combined_for_the_widgets(self): + recipe = self._recipe() + recipe = replace(recipe, config=replace( + recipe.config, offset_x=2.0, offset_y=-1.0, offset_z=1.0, + )) + _, stored = app_helpers.project_session_state(recipe, ["first", "second"]) + assert [stored["first"][f"offset_{axis}"] for axis in "xyz"] == [3.0, 1.0, 4.0] + assert [stored["second"][f"offset_{axis}"] for axis in "xyz"] == [1.0, -1.0, 5.0] + + @pytest.mark.parametrize("shape,dimensions", [ + ("box", {"box_height": 30.0}), + ("box", {"box_width": 50.0}), + ("box", {"box_width": 50.0, "box_depth": 60.0}), + ("cylinder", {"box_height": 30.0}), + ("cylinder", {"box_diameter": 60.0}), + ]) + def test_partial_active_box_dimensions_are_rejected(self, shape, dimensions): + recipe = self._recipe() + recipe = replace(recipe, config=replace(recipe.config, box_shape=shape, **dimensions)) + with pytest.raises(inlayer_project.ProjectError, match="box_"): + app_helpers.project_session_state(recipe, ["first", "second"]) + + @pytest.mark.parametrize("shape,dimensions", [ + ("box", {"box_diameter": 80.0}), + ("cylinder", {"box_width": 80.0, "box_depth": 60.0}), + ]) + def test_inactive_dimensions_do_not_enable_a_custom_box(self, shape, dimensions): + recipe = self._recipe() + recipe = replace(recipe, config=replace(recipe.config, box_shape=shape, **dimensions)) + values, _ = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["use_custom_box"] is False + + @pytest.mark.parametrize("shape,dimensions", [ + ("box", {"box_width": 50.0, "box_depth": 60.0, "box_height": 30.0}), + ("cylinder", {"box_diameter": 60.0, "box_height": 30.0}), + ]) + def test_complete_active_box_dimensions_are_preserved(self, shape, dimensions): + recipe = self._recipe() + recipe = replace(recipe, config=replace(recipe.config, box_shape=shape, **dimensions)) + values, _ = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["use_custom_box"] is True + assert all(values[field] == value for field, value in dimensions.items()) + + @pytest.mark.parametrize("field,value", [ + ("clearance", 0.25), + ("decimate_faces", 1000), + ("rotation", 12.5), + ("offset", 0.5), + ("finger_recess_position", 0.12), + ]) + def test_values_the_widgets_would_change_are_rejected(self, field, value): + recipe = self._recipe() + if field in inlayer.Config.__dataclass_fields__ and field != "finger_recess_position": + recipe = replace(recipe, config=replace(recipe.config, **{field: value})) + else: + first = recipe.figures[0] + changed = {"finger_recess_position": value} if field == "finger_recess_position" else { + field: (value, *getattr(first, field)[1:]), + } + recipe = replace(recipe, figures=(replace(first, **changed), *recipe.figures[1:])) + with pytest.raises(inlayer_project.ProjectError) as error: + app_helpers.project_session_state(recipe, ["first", "second"]) + assert field.split("_")[0] in str(error.value) + + class TestPreviewCopy: def test_never_the_input_and_no_metadata(self): """Below the face budget decimate_mesh returns its input - the cache diff --git a/tests/test_app_render.py b/tests/test_app_render.py index 008602c..07e09cd 100644 --- a/tests/test_app_render.py +++ b/tests/test_app_render.py @@ -12,6 +12,7 @@ import ast import base64 +import io import json from pathlib import Path from typing import cast @@ -24,6 +25,7 @@ import app_helpers import i18n import inlayer +import inlayer_project from tests.conftest import binary_stl APP = str(Path(__file__).resolve().parent.parent / "app.py") @@ -47,6 +49,37 @@ def _upload(at: AppTest, files: list[tuple[str, bytes]]) -> AppTest: return at +def _open_project( + at: AppTest, files: list[tuple[str, bytes]], recipe: str | bytes +) -> AppTest: + """Upload the recipe and all its sources together, as after a restart.""" + recipe_bytes = recipe.encode("utf-8") if isinstance(recipe, str) else recipe + at.file_uploader[0].set_value([(name, data, "model/stl") for name, data in files]) + at.file_uploader[1].set_value(("project.json", recipe_bytes, "application/json")) + at.run() + assert not at.exception, [str(e.value) for e in at.exception] + return at + + +def _project_recipe(files: list[tuple[str, bytes]]) -> str: + config = inlayer.Config( + clearance=0.5, wall_thickness=2.0, depth_fraction=0.75, + voxel_pitch=1.0, decimate_faces=5000, figure_gap=2.5, + enable_finger_recesses=True, finger_radius=5.0, finger_recess_z_offset=1.0, + ) + sources = [ + inlayer_project.SourceIdentity(name, inlayer_project.bytes_hash(data)) + for name, data in files + ] + recipe = inlayer_project.new_project( + config, sources, + rotations=[(10.0, 20.0, 30.0), (0.0, 15.0, 90.0)], + offsets=[(1.0, 0.0, 0.0), (0.0, 2.0, 0.0)], + recess_positions=[0.25, -0.25], figure_ids=["figure-one", "figure-two"], + ) + return inlayer_project.dumps_project(recipe) + + def _checkbox(at: AppTest, key: str): label = i18n.TRANSLATIONS[key][i18n.get_language()] return next(c for c in at.sidebar.checkbox if c.label == label) @@ -750,6 +783,159 @@ def test_widgets_start_with_the_pipeline_defaults(): assert _widget(at, kind, key).value == getattr(cfg, field), key +class TestProjectRecipes: + @staticmethod + def _files() -> list[tuple[str, bytes]]: + return [ + ("model.stl", _stl([10, 10, 10])), + ("model.stl", _stl([20, 6, 4])), + ] + + def test_same_named_sources_import_in_reverse_order_and_export_stable_ids(self): + files = self._files() + source_recipe = _project_recipe(files) + expected = inlayer_project.loads_project(source_recipe) + at = _open_project(_run("en"), list(reversed(files)), source_recipe) + assert not at.error + + upload_by_project = { + project_id: upload_id + for upload_id, project_id in at.session_state["_project_id_by_file_id"].items() + } + assert set(upload_by_project) == {"figure-one", "figure-two"} + first = at.session_state["fig_offsets_dict"][upload_by_project["figure-one"]] + second = at.session_state["fig_offsets_dict"][upload_by_project["figure-two"]] + assert (first["rot_x"], first["rot_y"], first["rot_z"]) == (10.0, 20.0, 30.0) + assert (second["rot_x"], second["rot_y"], second["rot_z"]) == (0.0, 15.0, 90.0) + assert (first["offset_x"], second["offset_y"]) == (1.0, 2.0) + assert first["finger_recess_position"] == 0.25 + assert second["finger_recess_position"] == -0.25 + + exported = inlayer_project.loads_project(at.session_state["_project_export"]) + assert exported.config == expected.config + assert [figure.id for figure in exported.figures] == ["figure-one", "figure-two"] + assert [figure.source.sha256 for figure in exported.figures] == [ + inlayer_project.bytes_hash(data) for _, data in files + ] + assert all(len(figure.source.sha256) == 64 for figure in exported.figures) + assert all(figure.source.path is None for figure in exported.figures) + assert [figure.rotation for figure in exported.figures] == [ + figure.rotation for figure in expected.figures + ] + assert [figure.offset for figure in exported.figures] == [ + figure.offset for figure in expected.figures + ] + assert _widget(at, "download_button", "project_download").label == ( + i18n.TRANSLATIONS["app.project.download"]["en"] + ) + + _widget(at, "selectbox", "ui_lang").set_value("de").run() + assert not at.exception + assert any(i18n.TRANSLATIONS["app.project.imported"]["de"].format(n=2) == item.value + for item in at.success) + _widget(at, "slider", "clearance").set_value(0.6).run() + assert _widget(at, "slider", "clearance").value == 0.6 + changed = inlayer_project.loads_project(at.session_state["_project_export"]) + assert changed.config.clearance == 0.6 + assert [figure.id for figure in changed.figures] == ["figure-one", "figure-two"] + + def test_automatic_gap_keeps_following_wall_thickness_after_reopening(self): + files = self._files() + recipe = json.loads(_project_recipe(files)) + recipe["config"]["figure_gap"] = None + original = _open_project(_run("en"), files, json.dumps(recipe)) + exported = original.session_state["_project_export"] + assert inlayer_project.loads_project(exported).config.figure_gap is None + + restarted = _open_project(_run("en"), files, exported) + _widget(restarted, "slider", "wall_thickness").set_value(3.0).run() + assert not restarted.exception + assert restarted.session_state["figure_gap"] == 3.0 + assert restarted.session_state["_gap_user_set"] is False + assert inlayer_project.loads_project( + restarted.session_state["_project_export"] + ).config.figure_gap is None + + def test_fresh_web_session_reproduces_geometry_and_wall_findings(self): + files = self._files() + original = _open_project(_run("en"), files, _project_recipe(files)) + original.button[0].click().run() + assert not original.exception and not original.error + assert "result" in original.session_state + first = original.session_state["result"] + exported = original.session_state["_project_export"] + + restarted = _open_project(_run("de"), list(reversed(files)), exported) + assert not restarted.error + restarted.button[0].click().run() + assert not restarted.exception and not restarted.error + second = restarted.session_state["result"] + for key in ("actual_w", "actual_d", "actual_h"): + assert second[key] == pytest.approx(first[key], abs=2e-3) + assert second["stats_3d"] == first["stats_3d"] + np.testing.assert_allclose(second["placements"], first["placements"], atol=2e-3) + np.testing.assert_allclose( + [mesh.extents for mesh in second["fig_viz"]], + [mesh.extents for mesh in first["fig_viz"]], atol=2e-3, + ) + + def measured(result): + mesh = trimesh.load(io.BytesIO(result["stl_bytes"]), file_type="stl", force="mesh") + assert isinstance(mesh, trimesh.Trimesh) + return mesh, np.concatenate([mesh.extents, [mesh.volume], mesh.center_mass]) + + original_mesh, original_signature = measured(first) + reopened_mesh, reopened_signature = measured(second) + np.testing.assert_allclose(reopened_signature, original_signature, rtol=1e-5, atol=2e-3) + np.testing.assert_allclose(reopened_mesh.bounds, original_mesh.bounds, atol=2e-3) + + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + @pytest.mark.parametrize("case", ["missing", "changed", "version", "web_value", "partial_box"]) + def test_invalid_project_or_source_stops_before_the_pipeline(self, lang, case, monkeypatch): + files = self._files() + recipe = _project_recipe(files) + supplied = files + expected_hash = inlayer_project.bytes_hash(files[0][1]) + if case == "missing": + supplied = [] + expected = i18n.TRANSLATIONS["project.source_not_provided"][lang].format( + name="model.stl", hash=expected_hash[:12], + ) + elif case == "changed": + supplied = [files[0], ("model.stl", _stl([30, 10, 10]))] + expected_hash = inlayer_project.bytes_hash(files[1][1]) + expected = i18n.TRANSLATIONS["project.source_not_provided"][lang].format( + name="model.stl", hash=expected_hash[:12], + ) + elif case == "version": + raw = json.loads(recipe) + raw["version"] = 99 + recipe = json.dumps(raw) + expected = i18n.TRANSLATIONS["project.unsupported_version"][lang].format(version=99) + elif case == "web_value": + raw = json.loads(recipe) + raw["config"]["clearance"] = 0.25 + recipe = json.dumps(raw) + expected = i18n.TRANSLATIONS["project.web_value"][lang].format(field="clearance") + else: + raw = json.loads(recipe) + raw["config"]["box_height"] = 30.0 + recipe = json.dumps(raw) + expected = i18n.TRANSLATIONS["project.web_value"][lang].format(field="box_width") + + def pipeline_must_not_start(*_args, **_kwargs): + raise AssertionError("the pipeline must not start") + + monkeypatch.setattr(inlayer, "prepare_figure", pipeline_must_not_start) + at = _open_project(_run(lang), supplied, recipe) + assert any(expected in item.value for item in at.error) + at.button[0].click().run() + assert not at.exception + assert any(expected in item.value for item in at.error) + assert "result" not in at.session_state + assert "_project_export" not in at.session_state + + def _badges(at: AppTest) -> list[str]: """The wall-check badges on the page (HTML of the markdown elements).""" return [m.value for m in at.markdown if '-badge">' in m.value] # not the stylesheet diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 657fe81..52d06b2 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -21,7 +21,7 @@ from inlayer import Config REPO_ROOT = Path(__file__).resolve().parent.parent -SOURCE_FILES = ("app.py", "inlayer.py", "app_helpers.py") +SOURCE_FILES = ("app.py", "inlayer.py", "app_helpers.py", "inlayer_project.py") # Keys the code only assembles at runtime (f-strings such as # t(f"app.layout.{x}")). The AST scan cannot resolve them, so they are listed diff --git a/tests/test_project.py b/tests/test_project.py new file mode 100644 index 0000000..e65b763 --- /dev/null +++ b/tests/test_project.py @@ -0,0 +1,581 @@ +"""Versioned project recipes and source identity checks.""" + +from __future__ import annotations + +import json +import subprocess +import sys +import uuid +from dataclasses import replace + +import numpy as np +import pytest +import trimesh + +import inlayer +import inlayer_project as project_module +from inlayer_project import ( + ProjectError, + SourceCandidate, + SourceIdentity, + dumps_project, + effective_offsets, + load_project, + loads_project, + match_project_sources, + new_project, + project_from_dict, + project_to_dict, + resolve_project_paths, + save_project, +) + + +def _stl(extents) -> bytes: + data = trimesh.creation.box(extents=extents).export(file_type="stl") + assert isinstance(data, bytes) + return data + + +def _config() -> inlayer.Config: + return inlayer.Config( + clearance=0.5, + wall_thickness=2.0, + depth_fraction=0.7, + voxel_pitch=1.0, + decimate_faces=5000, + stl_unit_to_mm=1.0, + figure_gap=2.5, + enable_finger_recesses=True, + finger_radius=5.0, + finger_recess_z_offset=1.0, + ) + + +def _sources(tmp_path, with_paths=True): + first = _stl([10, 10, 10]) + second = _stl([20, 6, 4]) + paths = [] + for directory, data in (("first", first), ("second", second)): + folder = tmp_path / directory + folder.mkdir() + path = folder / "model.stl" + path.write_bytes(data) + paths.append(str(path)) + sources = [ + SourceIdentity("model.stl", project_module.bytes_hash(data), path if with_paths else None) + for data, path in zip((first, second), paths) + ] + return first, second, paths, sources + + +def _project(tmp_path, with_paths=True): + first, second, paths, sources = _sources(tmp_path, with_paths) + recipe_path = tmp_path / "recipe.json" if with_paths else None + recipe = new_project( + _config(), sources, + rotations=[(10.0, 20.0, 30.0), (0.0, 15.0, 90.0)], + offsets=[(1.0, 0.0, 0.0), (0.0, 2.0, 0.0)], + recess_positions=[0.25, -0.25], + figure_ids=["figure-one", "figure-two"], + project_path=recipe_path, + ) + return recipe, (first, second, paths) + + +class TestRoundTrip: + def test_config_sources_and_individual_settings_survive(self, tmp_path): + recipe, _ = _project(tmp_path) + restored = loads_project(dumps_project(recipe)) + assert restored == recipe + assert restored.version == project_module.PROJECT_VERSION == 1 + assert restored.config == _config() + assert [figure.id for figure in restored.figures] == ["figure-one", "figure-two"] + assert [figure.source.name for figure in restored.figures] == ["model.stl", "model.stl"] + assert restored.figures[0].source.sha256 != restored.figures[1].source.sha256 + assert restored.figures[0].rotation == (10.0, 20.0, 30.0) + assert restored.figures[1].offset == (0.0, 2.0, 0.0) + assert restored.figures[0].finger_recess_position == 0.25 + assert restored.figures[1].finger_recess_position == -0.25 + + def test_every_config_field_is_in_the_recipe(self, tmp_path): + raw = project_to_dict(_project(tmp_path)[0]) + assert set(raw) == {"format", "version", "config", "figures"} + assert raw["format"] == "inlayer-project" + assert set(raw["config"]) == set(inlayer.Config.__dataclass_fields__) + assert set(raw["figures"][0]) == { + "id", "source", "rotation", "offset", "finger_recess_position" + } + + def test_generated_ids_are_persistent_uuids_not_upload_ids(self, tmp_path): + _, _, _, sources = _sources(tmp_path, with_paths=False) + recipe = new_project(_config(), sources, figure_ids=None) + ids = [figure.id for figure in recipe.figures] + assert len(set(ids)) == 2 + assert all(str(uuid.UUID(value)) == value for value in ids) + assert loads_project(dumps_project(recipe)).figures == recipe.figures + + def test_unicode_names_and_null_paths_round_trip(self, tmp_path): + source = SourceIdentity("Figur-ä.stl", project_module.bytes_hash(_stl([1, 2, 3]))) + recipe = new_project(_config(), [source]) + path = tmp_path / "Projekt.json" + save_project(recipe, path) + assert load_project(path) == recipe + assert json.loads(path.read_text(encoding="utf-8"))["figures"][0]["source"]["path"] is None + + def test_global_and_individual_offsets_add_exactly_once(self, tmp_path): + recipe, _ = _project(tmp_path) + config = replace(recipe.config, offset_x=3.0, offset_y=-1.0, offset_z=2.0) + recipe = new_project( + config, [figure.source for figure in recipe.figures], + rotations=[figure.rotation for figure in recipe.figures], + offsets=[figure.offset for figure in recipe.figures], + recess_positions=[figure.finger_recess_position for figure in recipe.figures], + figure_ids=[figure.id for figure in recipe.figures], + ) + assert effective_offsets(recipe) == [(4.0, -1.0, 2.0), (3.0, 1.0, 2.0)] + + +class TestValidation: + def test_future_version_is_an_explicit_compatibility_error(self, tmp_path): + raw = project_to_dict(_project(tmp_path)[0]) + raw["version"] = 2 + with pytest.raises(ProjectError, match="version 2"): + project_from_dict(raw) + + @pytest.mark.parametrize("value", [0, True, 1.0, "1"]) + def test_version_must_be_the_integer_one(self, tmp_path, value): + raw = project_to_dict(_project(tmp_path)[0]) + raw["version"] = value + with pytest.raises(ProjectError): + project_from_dict(raw) + + @pytest.mark.parametrize("section,key", [ + ("top", "unexpected"), + ("config", "unexpected"), + ("figure", "unexpected"), + ("source", "unexpected"), + ]) + def test_unknown_fields_are_rejected(self, tmp_path, section, key): + raw = project_to_dict(_project(tmp_path)[0]) + target = { + "top": raw, + "config": raw["config"], + "figure": raw["figures"][0], + "source": raw["figures"][0]["source"], + }[section] + target[key] = True + with pytest.raises(ProjectError, match=key): + project_from_dict(raw) + + def test_missing_field_names_its_path(self, tmp_path): + raw = project_to_dict(_project(tmp_path)[0]) + del raw["figures"][0]["source"]["sha256"] + with pytest.raises(ProjectError, match=r"figures\[0\].source.sha256"): + project_from_dict(raw) + + @pytest.mark.parametrize("value", [True, "2", None, float("nan"), float("inf")]) + def test_config_numbers_are_finite_json_numbers_not_booleans(self, tmp_path, value): + raw = project_to_dict(_project(tmp_path)[0]) + raw["config"]["wall_thickness"] = value + with pytest.raises(ProjectError): + project_from_dict(raw) + + @pytest.mark.parametrize("field", ["wall_thickness", "rotation"]) + def test_overflowing_numbers_are_project_errors(self, tmp_path, field): + raw = project_to_dict(_project(tmp_path)[0]) + if field == "rotation": + raw["figures"][0]["rotation"][0] = 10 ** 400 + else: + raw["config"][field] = 10 ** 400 + with pytest.raises(ProjectError, match=field): + loads_project(json.dumps(raw)) + + def test_json_integer_digit_limit_is_a_project_error(self): + with pytest.raises(ProjectError, match="UTF-8 JSON"): + loads_project('{"version":' + "1" * 5000 + "}") + + @pytest.mark.parametrize("escaped", [False, True]) + def test_unpaired_unicode_surrogates_are_project_errors(self, tmp_path, escaped): + raw = project_to_dict(_project(tmp_path)[0]) + raw["figures"][0]["source"]["name"] = "\ud800.stl" + with pytest.raises(ProjectError): + loads_project(json.dumps(raw, ensure_ascii=escaped)) + + @pytest.mark.parametrize("value", [True, 20000.0, "20000"]) + def test_decimation_is_an_integer(self, tmp_path, value): + raw = project_to_dict(_project(tmp_path)[0]) + raw["config"]["decimate_faces"] = value + with pytest.raises(ProjectError): + project_from_dict(raw) + + @pytest.mark.parametrize("hash_value", ["abc", "z" * 64, 42, None]) + def test_source_identity_requires_a_full_sha256(self, tmp_path, hash_value): + raw = project_to_dict(_project(tmp_path)[0]) + raw["figures"][0]["source"]["sha256"] = hash_value + with pytest.raises(ProjectError, match="sha256"): + project_from_dict(raw) + + def test_duplicate_figure_ids_are_rejected(self, tmp_path): + raw = project_to_dict(_project(tmp_path)[0]) + raw["figures"][1]["id"] = raw["figures"][0]["id"] + with pytest.raises(ProjectError, match="duplicate"): + project_from_dict(raw) + + @pytest.mark.parametrize("position", [-1.1, 1.1, float("nan")]) + def test_individual_recess_positions_are_validated(self, tmp_path, position): + raw = project_to_dict(_project(tmp_path)[0]) + raw["figures"][0]["finger_recess_position"] = position + with pytest.raises(ProjectError): + project_from_dict(raw) + + def test_invalid_utf8_and_json_are_plain_errors(self): + with pytest.raises(ProjectError, match="UTF-8 JSON"): + loads_project(b"\xff") + with pytest.raises(ProjectError, match="UTF-8 JSON"): + loads_project("{") + with pytest.raises(ProjectError, match="exceeds"): + loads_project(b" " * (project_module.MAX_PROJECT_BYTES + 1)) + + def test_constructor_rejects_missing_per_figure_values(self, tmp_path): + _, _, _, sources = _sources(tmp_path, with_paths=False) + with pytest.raises(ProjectError, match="figures"): + new_project(_config(), sources, rotations=[]) + + +class TestSourceResolution: + def test_same_names_different_content_match_by_hash_not_upload_order(self, tmp_path): + recipe, (first, second, _) = _project(tmp_path) + candidates = [ + SourceCandidate("model.stl", project_module.bytes_hash(second)), + SourceCandidate("model.stl", project_module.bytes_hash(first)), + ] + matches = match_project_sources(recipe, candidates) + assert [match.candidate_index for match in matches] == [1, 0] + assert [match.figure.id for match in matches] == ["figure-one", "figure-two"] + + def test_reversed_explicit_paths_still_build_in_project_order(self, tmp_path): + recipe, (_, _, paths) = _project(tmp_path) + resolved = resolve_project_paths(recipe, list(reversed(paths)), project_path=tmp_path / "recipe.json") + assert [match.path for match in resolved] == paths + assert [match.figure.id for match in resolved] == ["figure-one", "figure-two"] + + def test_relative_paths_follow_the_recipe_not_the_process_cwd(self, tmp_path, monkeypatch): + recipe, (_, _, paths) = _project(tmp_path) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + resolved = resolve_project_paths(recipe, None, project_path=tmp_path / "recipe.json") + assert [match.path for match in resolved] == paths + + def test_changed_stored_source_is_detected_before_resolution(self, tmp_path): + recipe, _ = _project(tmp_path) + changed = tmp_path / recipe.figures[0].source.path + changed.write_bytes(_stl([30, 10, 10])) + with pytest.raises(ProjectError, match="changed"): + resolve_project_paths(recipe, None, project_path=tmp_path / "recipe.json") + + def test_removed_stored_source_names_figure_and_path(self, tmp_path): + recipe, _ = _project(tmp_path) + (tmp_path / recipe.figures[0].source.path).unlink() + with pytest.raises(ProjectError, match="not found") as error: + resolve_project_paths(recipe, None, project_path=tmp_path / "recipe.json") + assert "model.stl" in str(error.value) + + def test_changed_upload_is_not_silently_used_for_another_figure(self, tmp_path): + recipe, (first, _, _) = _project(tmp_path) + changed = _stl([30, 10, 10]) + candidates = [ + SourceCandidate("model.stl", project_module.bytes_hash(first)), + SourceCandidate("model.stl", project_module.bytes_hash(changed)), + ] + with pytest.raises(ProjectError, match="expected SHA-256"): + match_project_sources(recipe, candidates) + + def test_extra_upload_is_an_error_not_a_silently_ignored_figure(self, tmp_path): + recipe, (first, second, _) = _project(tmp_path) + candidates = [ + SourceCandidate("model.stl", project_module.bytes_hash(first)), + SourceCandidate("model.stl", project_module.bytes_hash(second)), + SourceCandidate("extra.stl", project_module.bytes_hash(_stl([1, 2, 3]))), + ] + with pytest.raises(ProjectError, match="extra.stl"): + match_project_sources(recipe, candidates) + + def test_identical_content_still_needs_one_source_per_project_figure(self, tmp_path): + source = SourceIdentity("same.stl", project_module.bytes_hash(_stl([10, 10, 10]))) + recipe = new_project(_config(), [source, source], figure_ids=["one", "two"]) + candidate = SourceCandidate(source.name, source.sha256) + with pytest.raises(ProjectError, match="expected SHA-256"): + match_project_sources(recipe, [candidate]) + matches = match_project_sources(recipe, [candidate, candidate]) + assert [match.figure.id for match in matches] == ["one", "two"] + + +class TestCLIProjects: + @staticmethod + def _signature(path): + mesh = trimesh.load(str(path), force="mesh") + assert isinstance(mesh, trimesh.Trimesh) + return np.concatenate([mesh.extents, [mesh.volume], mesh.center_mass]) + + def test_restart_reopens_same_named_sources_and_individual_settings( + self, tmp_path, capsys, monkeypatch + ): + """The reopened CLI run is a real subprocess with another cwd.""" + from tests.test_pipeline import run_main + + recipe, _ = _project(tmp_path) + initial = tmp_path / "initial.json" + exported = tmp_path / "exported.json" + original_stl = tmp_path / "original.stl" + save_project(recipe, initial) + reports = [] + real_stats = inlayer.wall_thickness_stats_3d + + def capture_stats(mesh): + report = real_stats(mesh) + reports.append(report) + return report + + monkeypatch.setattr(inlayer, "wall_thickness_stats_3d", capture_stats) + code, stdout, stderr = run_main( + capsys, "--project", initial, "-o", original_stl, "--save-project", exported + ) + assert code == inlayer.EXIT_CHECK_FAILED, stdout + stderr + assert reports[0]["passes_min_wall"] is False + assert [(v["kind"], v["measured_mm"]) for v in reports[0]["violations"]] == [ + ("side", 1.0), ("inner", 0.5), + ] + assert load_project(exported) == recipe + + elsewhere = tmp_path / "restart" + elsewhere.mkdir() + reopened_stl = tmp_path / "reopened.stl" + result = subprocess.run( + [sys.executable, inlayer.__file__, "--project", str(exported), "-o", str(reopened_stl)], + cwd=elsewhere, capture_output=True, text=True, timeout=120, + ) + assert result.returncode == code, result.stdout + result.stderr + assert "verified all 2 source files by SHA-256" in result.stdout + assert "side wall 1.00 mm" in result.stdout + assert "0.50 mm" in result.stdout + assert "[1/4]" in result.stdout + np.testing.assert_allclose( + self._signature(reopened_stl), self._signature(original_stl), rtol=1e-5, atol=2e-3 + ) + reopened_mesh = trimesh.load(str(reopened_stl), force="mesh") + original_mesh = trimesh.load(str(original_stl), force="mesh") + assert isinstance(reopened_mesh, trimesh.Trimesh) + assert isinstance(original_mesh, trimesh.Trimesh) + np.testing.assert_allclose(reopened_mesh.bounds, original_mesh.bounds, atol=2e-3) + + def test_web_recipe_reopens_in_cli_with_the_same_pockets_and_wall_findings( + self, tmp_path, capsys, monkeypatch + ): + """Rotations must not make the two entry points sort figures differently.""" + import io + + from tests import geometry_probe as probe + from tests.test_app_render import _open_project, _run + from tests.test_pipeline import run_main + + recipe, (first, second, paths) = _project(tmp_path) + files = [("model.stl", first), ("model.stl", second)] + web = _open_project(_run("en"), files, dumps_project(recipe)) + web.button[0].click().run() + assert not web.exception and not web.error + web_result = web.session_state["result"] + web_mesh = trimesh.load( + io.BytesIO(web_result["stl_bytes"]), file_type="stl", force="mesh", + ) + assert isinstance(web_mesh, trimesh.Trimesh) + recipe_path = tmp_path / "web.json" + recipe_path.write_text(web.session_state["_project_export"], encoding="utf-8") + cli_path = tmp_path / "cli.stl" + reports = [] + real_stats = inlayer.wall_thickness_stats_3d + + def capture_stats(mesh): + report = real_stats(mesh) + reports.append(report) + return report + + monkeypatch.setattr(inlayer, "wall_thickness_stats_3d", capture_stats) + code, stdout, stderr = run_main( + capsys, "--project", recipe_path, "-i", *reversed(paths), "-o", cli_path, + ) + assert code == inlayer.EXIT_CHECK_FAILED, stdout + stderr + assert reports == [web_result["stats_3d"]] + cli_mesh = trimesh.load(str(cli_path), force="mesh") + assert isinstance(cli_mesh, trimesh.Trimesh) + np.testing.assert_allclose(cli_mesh.bounds, web_mesh.bounds, atol=2e-3) + dimensions = web_mesh.extents + assert probe.outer_walls(cli_mesh, *dimensions) == pytest.approx( + probe.outer_walls(web_mesh, *dimensions), abs=2e-3, + ) + assert probe.inner_gap(cli_mesh, *dimensions) == pytest.approx( + probe.inner_gap(web_mesh, *dimensions), abs=2e-3, + ) + cli_solid, web_solid = probe.to_manifold(cli_mesh), probe.to_manifold(web_mesh) + assert (cli_solid - web_solid).volume() < 2e-3 + assert (web_solid - cli_solid).volume() < 2e-3 + + def test_export_from_flags_preserves_hashes_rotation_offsets_and_grips( + self, tmp_path, capsys + ): + from tests.test_pipeline import run_main + + _, (_, _, paths) = _project(tmp_path) + output = tmp_path / "inlay.stl" + recipe_path = tmp_path / "flags.json" + code, stdout, stderr = run_main( + capsys, "-i", paths[0], "-o", output, "--save-project", recipe_path, + "--voxel-pitch", "1", "--decimate-faces", "5000", "--rot-x", "10", + "--rot-y", "20", "--rot-z", "30", "--offset-x", "1", "--offset-y", "2", + "--offset-z", "0.5", "--finger-recesses", "--finger-radius", "5", + "--finger-recess-position", "0.25", + ) + assert code == inlayer.EXIT_CHECK_FAILED, stdout + stderr + raw = json.loads(recipe_path.read_text(encoding="utf-8")) + assert len(raw["figures"][0]["source"]["sha256"]) == 64 + assert raw["figures"][0]["source"]["name"] == "model.stl" + assert raw["figures"][0]["rotation"] == [10.0, 20.0, 30.0] + assert raw["figures"][0]["offset"] == [0.0, 0.0, 0.0] + assert raw["figures"][0]["finger_recess_position"] == 0.25 + assert raw["config"]["offset_x"] == 1.0 + assert raw["config"]["offset_y"] == 2.0 + assert raw["config"]["offset_z"] == 0.5 + assert str(uuid.UUID(raw["figures"][0]["id"])) == raw["figures"][0]["id"] + + def test_changed_source_stops_before_the_first_pipeline_step( + self, tmp_path, capsys, monkeypatch + ): + from tests.test_pipeline import run_main + + recipe, _ = _project(tmp_path) + path = tmp_path / "recipe.json" + save_project(recipe, path) + (tmp_path / recipe.figures[0].source.path).write_bytes(_stl([30, 10, 10])) + + def pipeline_must_not_start(*_args, **_kwargs): + raise AssertionError("pipeline started") + + monkeypatch.setattr(inlayer, "prepare_figure", pipeline_must_not_start) + code, stdout, stderr = run_main(capsys, "--project", path, "-o", tmp_path / "out.stl") + assert code == 2 + assert "changed" in stderr + assert "[1/4]" not in stdout + assert not (tmp_path / "out.stl").exists() + + @pytest.mark.parametrize("positions", [["0.2"], ["0.1", "0.2"]]) + def test_export_keeps_disabled_recess_positions_ignored( + self, tmp_path, capsys, cube_stl_path, positions, + ): + from tests.test_pipeline import run_main + + destination = tmp_path / "recipe.json" + code, stdout, stderr = run_main( + capsys, "-i", cube_stl_path, "-o", tmp_path / "out.stl", + "--voxel-pitch", "1", "--decimate-faces", "1000", + "--finger-recess-position", *positions, "--save-project", destination, + ) + assert code == 0, stdout + stderr + assert "ignored" in stdout + recipe = load_project(destination) + assert not recipe.config.enable_finger_recesses + assert [figure.finger_recess_position for figure in recipe.figures] == [ + recipe.config.finger_recess_position, + ] + + def test_incompatible_version_stops_before_the_pipeline(self, tmp_path, capsys, monkeypatch): + from tests.test_pipeline import run_main + + recipe, _ = _project(tmp_path) + raw = project_to_dict(recipe) + raw["version"] = 99 + path = tmp_path / "future.json" + path.write_text(json.dumps(raw), encoding="utf-8") + monkeypatch.setattr( + inlayer, "prepare_figure", + lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("pipeline started")), + ) + code, stdout, stderr = run_main(capsys, "--project", path, "-o", tmp_path / "out.stl") + assert code == 2 + assert "version 99" in stderr + assert "[1/4]" not in stdout + + @pytest.mark.parametrize("flag", [ + ["--clearance", "0.4"], ["--clearance=0.4"], ["--clearanc", "0.4"], + ["-c0.4"], ["-w2.0"], ["--par"], ["--rot-x=0"], + ]) + def test_project_cannot_be_silently_overridden_by_a_config_flag( + self, tmp_path, capsys, monkeypatch, flag, + ): + from tests.test_pipeline import run_main + + recipe, _ = _project(tmp_path) + path = tmp_path / "recipe.json" + save_project(recipe, path) + monkeypatch.setattr( + inlayer, "prepare_figure", + lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("pipeline started")), + ) + code, stdout, stderr = run_main( + capsys, "--project", path, "-o", tmp_path / "out.stl", *flag, + ) + assert code == 2 + assert "cannot be combined" in stderr + assert "[1/4]" not in stdout + + @pytest.mark.parametrize("target", ["input", "output"]) + @pytest.mark.parametrize("alias", ["same_path", "symlink", "hardlink"]) + def test_project_export_cannot_overwrite_a_source_or_the_stl_output( + self, tmp_path, capsys, monkeypatch, target, alias, + ): + from pathlib import Path + + from tests.test_pipeline import run_main + + _, (_, _, paths) = _project(tmp_path) + output = tmp_path / "out.stl" + output.write_bytes(b"existing STL output") + protected = Path(paths[0]) if target == "input" else output + original = protected.read_bytes() + destination = protected + if alias != "same_path": + destination = tmp_path / "recipe.json" + if alias == "symlink": + destination.symlink_to(protected) + else: + destination.hardlink_to(protected) + monkeypatch.setattr( + inlayer, "prepare_figure", + lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("pipeline started")), + ) + code, stdout, stderr = run_main( + capsys, "-i", *paths, "-o", output, "--save-project", destination, + ) + assert code == 2 + assert "conflicts" in stderr + assert "[1/4]" not in stdout + assert protected.read_bytes() == original + assert output.read_bytes() == b"existing STL output" + + def test_unwritable_project_destination_is_rejected_before_the_pipeline( + self, tmp_path, capsys, monkeypatch + ): + from tests.test_pipeline import run_main + + _, (_, _, paths) = _project(tmp_path) + monkeypatch.setattr( + inlayer, "prepare_figure", + lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("pipeline started")), + ) + code, stdout, stderr = run_main( + capsys, "-i", paths[0], "-o", tmp_path / "out.stl", + "--save-project", tmp_path / "missing" / "recipe.json", + ) + assert code == 2 + assert "Cannot write" in stderr + assert "[1/4]" not in stdout diff --git a/tests/test_streamlit_config.py b/tests/test_streamlit_config.py index 16c72d4..75cda91 100644 --- a/tests/test_streamlit_config.py +++ b/tests/test_streamlit_config.py @@ -123,7 +123,7 @@ def test_no_deprecated_use_container_width_api(): Streamlit warns on every session start and drops the parameter in an upcoming release; a regression would otherwise only surface in the log. """ - sources = ["app.py", "app_helpers.py", "i18n.py", "inlayer.py"] + sources = ["app.py", "app_helpers.py", "i18n.py", "inlayer.py", "inlayer_project.py"] hits = [ name for name in sources if "use_container_width" in (_REPO_ROOT / name).read_text(encoding="utf-8") From 2cc3a3da6f1e2775bdf5f53f28c66f828eb3897b Mon Sep 17 00:00:00 2001 From: Rigare <19714539+Rigare@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:40:23 +0000 Subject: [PATCH 2/2] fix: preserve valid CLI project values in web sessions --- AGENTS.md | 3 +- README.md | 30 ++--- app.py | 149 +++++++++++++++++++----- app_helpers.py | 139 +++++++++-------------- i18n.py | 14 +-- tests/test_app_helpers.py | 59 ++++++++-- tests/test_app_render.py | 102 ++++++++++++++--- tests/test_project.py | 233 +++++++++++++++++++++++++++++++++++++- 8 files changed, 565 insertions(+), 164 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 20d96d8..a6b7c32 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,7 @@ High-signal context for OpenCode sessions in this repo. - `inlayer.py` is the pipeline library module. It exposes a frozen `Config` dataclass plus pipeline functions (`apply_euler_rotation`, `prepare_figure`, `dilate`, `build_inlay`, `wall_thickness_stats_3d`; `arrange_footprints` is the layout `build_inlay` uses). All parameters flow through `Config`. - `inlayer_project.py` owns the strict, versioned JSON recipe shared by CLI and Web (format `inlayer-project`, version 1): every `Config` field, stable figure ids, full SHA-256 source identities and individual rotations, offsets and grip positions. It imports `Config`; `inlayer.main` imports it lazily to avoid a module cycle. Recipes contain no STL bytes. Matching is by full content hash, never name or upload order; CLI-relative paths start at the recipe directory. Figure offsets are additions to the global `Config.offset_*` and `effective_offsets` combines them exactly once. Web uploads have no persisted local path. Unknown fields and unsupported versions are errors, not migration guesses. -- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`/`bytes_hash`, `quantize_axis_value`, `resolve_selection`, `applied_figure_params`, `project_session_state`, `figure_labels`, `load_preview_mesh`, `preview_copy`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.) +- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`/`bytes_hash`, `quantize_axis_value`, `resolve_selection`, `applied_figure_params`, `project_session_state`, `project_widget_value`, `figure_labels`, `load_preview_mesh`, `preview_copy`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.) - `app.py` is a Streamlit frontend. It builds an `inlayer.Config` from the sidebar widgets and passes it into the pipeline functions (no global mutation). Its widgets start at `Config`'s defaults (`inlayer.Config.`, read the way the CLI reads them), never at literals of their own: `tests/test_app_render.py` checks that the widgets start from `Config`'s values, `tests/test_pipeline.py::TestCLIDefaults` that the parser does. The same goes for a default quoted in a help text - pass it into the translation (`default=Config.`), don't type it into `i18n.py`. - `i18n.py` holds the **bilingual UI** (English/German). `t(key, **kwargs)` looks up `TRANSLATIONS` and fills named placeholders; unknown keys return the key itself rather than raising, so a missing string can never abort a running computation. Keys are namespaced `app.*` / `cli.*` / `pipeline.*` / `config.*` / `error.*` / `check.*` (wall-check findings, shared by CLI and app through `inlayer.describe_violation`). - **The current language is a `ContextVar`, not a module global.** Streamlit runs each session's script in its own thread; a shared global would let one session's language selection bleed into another's. Do not "simplify" this into a plain variable. @@ -50,6 +50,7 @@ High-signal context for OpenCode sessions in this repo. - **Every widget in `app.py` has a fixed, language-independent `key`.** Streamlit derives an unkeyed widget's identity from its label, which is translated: a language switch created new widgets, the uploads vanished and every setting fell back to its default. `tests/test_app_render.py` fails on a widget call without `key=`. - **Per-figure settings belong to an upload (`UploadedFile.file_id`), not to a file name.** `fig_offsets_dict` is keyed by id; entries of removed uploads are deleted (re-uploading starts from the defaults), duplicate names are shown as `model.stl (2)` (`figure_labels`). Two different `model.stl` files used to share one entry and moved together. - **Project ids and project hashes are not cache ids.** `project_session_state` maps persistent recipe ids to transient upload ids only once per changed import; `_project_id_by_file_id` retains them for later exports and `_fallback_project_id` identifies the fallback figure. Never serialize an upload id. The existing 16-character `content_hashes` still key caches and freshness; `_project_hash_by_file_id` and `_fallback_project_hash` hold separate full SHA-256 identities for recipes. `_current_config()` is shared by run and export; `_project_config()` additionally retains hidden multi-figure choices without changing the run. +- **Imported recipes are independent of widget limits.** `_project_config_base` retains the exact validated `Config`; `_project_config_edits` retains values from deliberate control edits, including while their widgets are hidden. `fig_offsets_dict` retains raw recipe figure values, with `_project_exact_figure_fields` protecting them from routine widget quantization. Controls receive separate editable projections through `project_widget_value`; a rerun, language switch or selection change must never replace exact imported values. Resolve the effective config before preparing, dilating, previewing, caching or taking a freshness snapshot. Preserve `None` for each automatic box/cylinder dimension and `figure_gap`. Combine global and individual offsets once for application; retain their separate raw values in recipe exports. Disabling manual offsets or rotations exports their effective zero values, since the recipe has no enable flag for them. Disabled recess values can remain raw because `Config.enable_finger_recesses` carries that state. - **Selections and sliders are reconciled with the uploads before any widget exists.** All three per-figure controls (recess position, offsets, rotation) resolve their selection through `app_helpers.resolve_selection` and reload their widgets from the stored values whenever the figure they show changes - including a removed upload, a new first figure under "all figures" and widget state dropped while hidden. Don't go back to loading in the selectbox `on_change` only: that missed every change to the file list, and the sliders then showed values the pipeline did not use. - **`app_helpers.applied_figure_params` is the only source of per-figure values.** The run, the instant preview and the staleness snapshot all read it - never a slider, which only shows the selected figure (reading the slider made a mere selection change look like a settings change). - **New user-facing text needs both languages.** `tests/test_i18n.py` fails on a missing translation, on placeholders that differ between languages, on positional `{}` placeholders, and on keys referenced in source but absent from the table. diff --git a/README.md b/README.md index df6f73a..ef863b3 100644 --- a/README.md +++ b/README.md @@ -298,11 +298,14 @@ their content differs. **A recipe is not an archive:** it contains no STL bytes and is not a ZIP file. To reopen a project in the web app, upload its JSON and exactly one original STL per project figure. The app checks every hash immediately; missing, -changed or additional sources and incompatible settings are reported in the +changed or additional sources and invalid recipes are reported in the sidebar, and *Generate* cannot start until the inputs match. Sources are then put into project order by content hash, never by name. The same recipe can be -exported again with the same stable ids. Disabled per-figure features are -saved with their effective zero values. +exported again with the same stable ids. Imported settings are retained exactly, +including values outside the ordinary controls and disabled finger-recess settings. +The controls show an editable approximation where necessary; only an explicit +edit replaces the corresponding imported value. Disabling manual offsets or +rotations exports their effective zero values, so reopening matches the web run. For the CLI, relative source paths are resolved from the **recipe's directory**, not the process's working directory. Web exports deliberately have no local @@ -315,20 +318,19 @@ The `--save-project` destination must differ from every STL input and the STL output; overwriting the opened JSON recipe itself is allowed. A figure's `offset` is its individual addition to `config.offset_x/y/z` and is -applied exactly once. The web UI has no separate global-offset controls, so -its exports carry the effective per-figure offsets shown there and zero global -offsets. +applied exactly once. Imported global and individual offsets remain separate +in exported recipes; the web controls edit each figure's individual addition. Version 1 is strict: malformed JSON, missing or unknown fields, invalid hashes and unsupported versions fail with a readable error instead of a best-guess -import. The web importer also rejects values outside its existing widget -ranges or between their steps (for example fractional-degree rotations or grip -positions not divisible by 5 %) rather than silently rounding them. Such -projects remain usable in the CLI when their `Config` is valid. A custom box -must specify all dimensions for its shape in the web app; partially automatic -dimensions remain a CLI feature. An automatic figure gap keeps following the -wall thickness after export and reopening. Reopening a -project preserves the computed geometry and wall findings within normal +import. Web and CLI accept the same valid recipe values, including fractional +rotations, offsets and grip positions and values beyond the usual web controls. +Box and cylinder dimensions can be independently fixed or automatic (`null`): +for example, a fixed height with automatic width and depth stays that way in +the web app and its exports. An automatic figure gap (`null`) keeps following +the wall thickness after export and reopening. Existing source checks, upload +limits and voxel-grid resource checks still apply. Reopening a project preserves +the computed geometry and wall findings within normal floating-point tolerances; STL byte-for-byte equality is not required. --- diff --git a/app.py b/app.py index 6bffc84..72bd0de 100644 --- a/app.py +++ b/app.py @@ -278,6 +278,8 @@ def log(self, msg, t0=None): st.sidebar.info(t("app.upload.multi_info", n=len(uploaded_files))) if project_notice is not None: st.sidebar.success(project_notice) +if "_project_config_base" in st.session_state: + st.sidebar.caption(t("app.project.controls")) # 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. @@ -321,8 +323,10 @@ def log(self, msg, t0=None): stored = st.session_state.setdefault("fig_offsets_dict", {}) # A removed upload takes its settings along; uploaded again, it starts fresh. +exact_figure_fields = st.session_state.setdefault("_project_exact_figure_fields", {}) for _gone in set(stored) - set(fig_ids): del stored[_gone] + exact_figure_fields.pop(_gone, None) for _fid in fig_ids: stored.setdefault(_fid, dict(app_helpers.FIGURE_DEFAULTS)) @@ -335,6 +339,46 @@ def _fig_label(fid: str) -> str: return _labels.get(fid, fid) +# Imported values live outside widget state; callbacks record deliberate edits. +_CONFIG_WIDGET_FIELDS = { + "scale": "stl_unit_to_mm", "finger_enabled": "enable_finger_recesses", + "finger_axis": "finger_recess_axis", "finger_z_offset": "finger_recess_z_offset", + "parallel": "enable_parallel", +} + + +def _mark_config_edit(*fields: str): + if "_project_config_base" not in st.session_state: + return + widget_keys = {field: key for key, field in _CONFIG_WIDGET_FIELDS.items()} + edits = st.session_state.setdefault("_project_config_edits", {}) + for field in fields: + edits[field] = st.session_state[widget_keys.get(field, field)] + + +def _edit_select(key: str, widget_key: str): + st.session_state[key] = st.session_state[widget_key] + if key not in STEP_DEFAULTS: + _mark_config_edit(_CONFIG_WIDGET_FIELDS.get(key, key)) + + +def _edit_number(key: str, stored_key: str): + st.session_state[stored_key] = st.session_state[key] + _mark_config_edit(_CONFIG_WIDGET_FIELDS.get(key, key)) + + +def _edit_custom_box(): + if "_project_config_base" not in st.session_state: + return + fields = ("box_diameter", "box_height") if st.session_state["box_shape"] == "cylinder" else ( + "box_width", "box_depth", "box_height", + ) + edits = st.session_state.setdefault("_project_config_edits", {}) + for field in fields: + edits[field] = (st.session_state[f"_{field}_value"] + if st.session_state["use_custom_box"] else None) + + def _select(label: str, labels: dict, key: str, default, **kwargs): """Selectbox over `labels` (value -> display text) whose value lives in a plain session key (`key`). @@ -356,7 +400,7 @@ def _select(label: str, labels: dict, key: str, default, **kwargs): index=options.index(st.session_state[key]), format_func=lambda v: labels.get(v, str(v)), key=widget_key, - on_change=lambda: st.session_state.update({key: st.session_state[widget_key]}), + on_change=_edit_select, args=(key, widget_key), **kwargs, ) @@ -369,7 +413,7 @@ def _persistent_number(widget, label: str, key: str, default: float, **kwargs): st.session_state[key] = st.session_state[stored_key] value = widget( label, key=key, - on_change=lambda: st.session_state.update({stored_key: st.session_state[key]}), + on_change=_edit_number, args=(key, stored_key), **kwargs, ) st.session_state[stored_key] = value @@ -394,17 +438,15 @@ def _quantize_axis(axis: str, val: float) -> float: def _requantize_axes(axes: tuple[str, ...]): - """Snaps every stored value and every display key to the current step. + """Snap native edits and display projections, preserving exact imports. - Runs on every rerun, before the sliders exist: that keeps what the sliders - show and what the pipeline reads identical, and keeps each value inside - its slider's range whatever step it was stored with. Writing the display - keys on every run also keeps them while their section is hidden - - Streamlit only drops the state of a hidden widget that nothing set. + Writing display keys also keeps them while a widget section is hidden. + Imported axes only enter the normal snapping behavior after an axis edit. """ - for offsets in stored.values(): + for fid, offsets in stored.items(): for axis in axes: - offsets[axis] = _quantize_axis(axis, offsets.get(axis, 0.0)) + if axis not in exact_figure_fields.get(fid, set()): + offsets[axis] = _quantize_axis(axis, offsets.get(axis, 0.0)) for axis in axes: if f"_sl_{axis}" in st.session_state: val = _quantize_axis(axis, st.session_state[f"_sl_{axis}"]) @@ -427,12 +469,20 @@ def _targets(sel_key: str) -> list[str]: def _load_axes(ref: str, axes: tuple[str, ...]): for axis in axes: - st.session_state[f"_sl_{axis}"] = stored[ref][axis] - st.session_state[f"_ni_{axis}"] = stored[ref][axis] + step_key = "rot_step" if axis in ROTATION_AXES else "pos_step" + step = float(st.session_state[step_key]) + lo, hi = ((0.0, 360.0 - step) if axis in ROTATION_AXES else + (-50.0, 150.0) if axis == "offset_z" else (-100.0, 100.0)) + value = app_helpers.project_widget_value(stored[ref][axis], 0.0, lo, hi, step) + st.session_state[f"_sl_{axis}"] = value + st.session_state[f"_ni_{axis}"] = value def _load_recess(ref: str): - st.session_state[RECESS_POS_KEY] = int(round(stored[ref]["finger_recess_position"] * 100)) + position = stored[ref]["finger_recess_position"] * 100 + st.session_state[RECESS_POS_KEY] = int(app_helpers.project_widget_value( + position, 0, -100, 100, 5, + )) def _store_axis_value(axis: str, val: float): @@ -443,6 +493,7 @@ def _store_axis_value(axis: str, val: float): st.session_state[f"_ni_{axis}"] = val for fid in _targets(app_helpers.selection_key(axis)): stored[fid][axis] = val + exact_figure_fields.get(fid, set()).discard(axis) def _sync_from_slider(axis: str): @@ -458,6 +509,7 @@ def _store_recess_position(): value = float(st.session_state[RECESS_POS_KEY]) / 100.0 for fid in _targets(RECESS_SELECT): stored[fid]["finger_recess_position"] = value + exact_figure_fields.get(fid, set()).discard("finger_recess_position") _requantize_axes(OFFSET_AXES + ROTATION_AXES) @@ -503,26 +555,32 @@ def _figure_select(label: str, sel_key: str): clearance = st.sidebar.slider( t("app.clearance.label"), min_value=0.1, max_value=2.0, step=0.1, value=inlayer.Config.clearance, help=t("app.clearance.help"), key="clearance", + on_change=_mark_config_edit, args=("clearance",), ) wall_thickness = st.sidebar.slider( t("app.wall_thickness.label"), min_value=1.0, max_value=5.0, step=0.5, value=inlayer.Config.wall_thickness, help=t("app.wall_thickness.help"), key="wall_thickness", + on_change=_mark_config_edit, args=("wall_thickness",), ) depth_fraction = st.sidebar.slider( t("app.depth_fraction.label"), min_value=0.3, max_value=1.0, step=0.05, value=inlayer.Config.depth_fraction, help=t("app.depth_fraction.help"), key="depth_fraction", + on_change=_mark_config_edit, args=("depth_fraction",), ) voxel_pitch = st.sidebar.slider( t("app.voxel_pitch.label"), min_value=0.2, max_value=1.0, step=0.1, value=inlayer.Config.voxel_pitch, help=t("app.voxel_pitch.help"), key="voxel_pitch", + on_change=_mark_config_edit, args=("voxel_pitch",), ) decimate_faces = st.sidebar.number_input( t("app.decimate_faces.label"), min_value=5000, max_value=50000, step=5000, value=inlayer.Config.decimate_faces, help=t("app.decimate_faces.help"), key="decimate_faces", + on_change=_mark_config_edit, args=("decimate_faces",), ) scale = st.sidebar.number_input( t("app.scale.label"), min_value=0.01, max_value=100.0, step=0.1, value=inlayer.Config.stl_unit_to_mm, help=t("app.scale.help"), key="scale", + on_change=_mark_config_edit, args=("stl_unit_to_mm",), ) # --- Finger recesses: position per figure ----------------------------------- @@ -530,7 +588,7 @@ def _figure_select(label: str, sel_key: str): t("app.finger.enable.label"), value=inlayer.Config.enable_finger_recesses, help=t("app.finger.enable.help"), - key="finger_enabled", + key="finger_enabled", on_change=_mark_config_edit, args=("enable_finger_recesses",), ) finger_radius = inlayer.Config.finger_radius finger_recess_axis = inlayer.Config.finger_recess_axis @@ -579,7 +637,7 @@ def _figure_select(label: str, sel_key: str): t("app.parallel.label"), value=inlayer.Config.enable_parallel, help=t("app.parallel.help", workers=inlayer.MAX_PARALLEL_WORKERS), - key="parallel", + key="parallel", on_change=_mark_config_edit, args=("enable_parallel",), ) st.sidebar.markdown("---") @@ -590,7 +648,9 @@ def _figure_select(label: str, sel_key: str): inlayer.Config.box_shape, help=t("app.box.shape.help"), ) -use_custom_box = st.sidebar.checkbox(t("app.box.custom.label"), value=False, key="use_custom_box") +use_custom_box = st.sidebar.checkbox( + t("app.box.custom.label"), value=False, key="use_custom_box", on_change=_edit_custom_box, +) box_width = None box_depth = None @@ -631,6 +691,7 @@ def _sync_gap(source: str): for key in GAP_KEYS: st.session_state[key] = val st.session_state["_gap_user_set"] = True + _mark_config_edit("figure_gap") # figure_gap only matters with several figures @@ -743,16 +804,9 @@ def _axis_row(axis: str, label: str, lo: float, hi: float, step: float, hint: st _axis_row("rot_y", t("app.rot_y.label"), 0.0, max_rot, rot_step, t("app.rot_y.help")) _axis_row("rot_z", t("app.rot_z.label"), 0.0, max_rot, rot_step, t("app.rot_z.help")) -# The per-figure values the pipeline really uses - the run, the instant preview -# and the staleness check all read these, never a slider. -applied = app_helpers.applied_figure_params( - stored, fig_ids, enable_manual_offsets, enable_manual_rotations, enable_finger_recesses -) - - def _current_config() -> inlayer.Config: - """The one configuration used by both the run and the project export.""" - return inlayer.Config( + """Exact imported configuration with only consciously edited fields replaced.""" + config = inlayer.Config( clearance=clearance, wall_thickness=wall_thickness, depth_fraction=depth_fraction, @@ -764,7 +818,7 @@ def _current_config() -> inlayer.Config: box_depth=box_depth, box_height=box_height, box_diameter=box_diameter, - figure_gap=figure_gap, + figure_gap=figure_gap if st.session_state.get("_gap_user_set") else None, layout_style=layout_style, enable_finger_recesses=enable_finger_recesses, finger_radius=finger_radius, @@ -772,11 +826,43 @@ def _current_config() -> inlayer.Config: finger_recess_z_offset=finger_recess_z_offset, enable_parallel=enable_parallel, ) + original = st.session_state.get("_project_config_base") + if original is not None: + config = replace(original, **st.session_state.get("_project_config_edits", {})) + if not enable_manual_offsets: + config = replace(config, offset_x=0.0, offset_y=0.0, offset_z=0.0) + return config + + +# Every caller, including preparation caches and the instant preview, uses the +# exact configuration rather than the editable widget projections above. +config = _current_config() +clearance, wall_thickness = config.clearance, config.wall_thickness +depth_fraction, voxel_pitch = config.depth_fraction, config.voxel_pitch +decimate_faces, scale = config.decimate_faces, config.stl_unit_to_mm +box_shape = config.box_shape +box_width, box_depth, box_height, box_diameter = ( + config.box_width, config.box_depth, config.box_height, config.box_diameter, +) +figure_gap, layout_style = config.figure_gap, config.layout_style +enable_finger_recesses, enable_parallel = config.enable_finger_recesses, config.enable_parallel +finger_radius, finger_recess_axis, finger_recess_z_offset = ( + config.finger_radius, config.finger_recess_axis, config.finger_recess_z_offset, +) + +# Globals and individual offsets combine only here; the recipe stores them +# separately and build_inlay consumes the combined offsets unchanged. +applied = app_helpers.applied_figure_params( + stored, fig_ids, enable_manual_offsets, enable_manual_rotations, enable_finger_recesses, + (config.offset_x, config.offset_y, config.offset_z), +) def _project_config() -> inlayer.Config: - """Keep hidden multi-figure choices without changing what a run uses.""" + """Retain hidden choices as well as exact imported project values.""" config = _current_config() + if "_project_config_base" in st.session_state: + return config return replace( config, figure_gap=float(st.session_state["figure_gap"]) @@ -804,11 +890,14 @@ def _project_json() -> str | None: sources = [inlayer_project.SourceIdentity(fallback_path, fallback_full_hash)] else: return None + raw = app_helpers.applied_figure_params( + stored, fig_ids, enable_manual_offsets, enable_manual_rotations, True, + ) recipe = inlayer_project.new_project( _project_config(), sources, - rotations=[values["rotation"] for values in applied], - offsets=[values["offset"] for values in applied], - recess_positions=[values["recess_position"] for values in applied], + rotations=[values["rotation"] for values in raw], + offsets=[values["offset"] for values in raw], + recess_positions=[values["recess_position"] for values in raw], figure_ids=figure_ids, ) return inlayer_project.dumps_project(recipe) diff --git a/app_helpers.py b/app_helpers.py index 2453842..58cf259 100644 --- a/app_helpers.py +++ b/app_helpers.py @@ -14,13 +14,10 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -"""Reine Hilfsfunktionen der Web-App – ohne Streamlit-Abhaengigkeit. +"""Streamlit-free web helpers, importable independently of the app sidebar. -`app.py` ruft beim Import `st.set_page_config()` auf und baut die gesamte -Sidebar auf Modul-Ebene. Dadurch laesst sich das Modul in Tests nicht -importieren. Alles, was keine Session-State- oder Widget-Zugriffe braucht, -liegt deshalb hier und wird von `app.py` importiert – so testet die Suite den -tatsaechlich ausgelieferten Code statt einer Kopie. +The app imports these functions so tests exercise the shipped implementation +without executing Streamlit widgets at import time. """ from __future__ import annotations @@ -113,90 +110,82 @@ def resolve_selection( def applied_figure_params( stored: dict[str, dict], fig_ids: list[str], offsets: bool, rotations: bool, recesses: bool, + global_offsets: tuple[float, float, float] = (0.0, 0.0, 0.0), ) -> list[dict]: """The per-figure values the pipeline really uses, in upload order. A disabled feature counts as zero, whatever is stored. The run, the instant preview and the "settings changed" check all read this - never - the slider, which only shows the currently selected figure. + the slider, which only shows the currently selected figure. Global offsets + are added here exactly once; stored values remain individual recipe values. """ applied = [] for fid in fig_ids: s = {**FIGURE_DEFAULTS, **stored.get(fid, {})} applied.append({ - "offset": tuple(float(s[a]) for a in OFFSET_AXES) if offsets else (0.0, 0.0, 0.0), + "offset": tuple(global_value + float(s[a]) for a, global_value in zip(OFFSET_AXES, global_offsets)) + if offsets else (0.0, 0.0, 0.0), "rotation": tuple(float(s[a]) for a in ROTATION_AXES) if rotations else (0.0, 0.0, 0.0), "recess_position": float(s["finger_recess_position"]) if recesses else 0.0, }) return applied +def project_widget_value(value, default, lo, hi, step=None): + """An editable widget projection, never a replacement for a recipe value. + + The existing controls cover a smaller range than Config. Keep incompatible + values outside widget state so Streamlit cannot reject or rewrite them. + """ + if value is None or not lo <= value <= hi: + return default + if step is not None: + steps = (value - lo) / step + if not math.isclose(steps, round(steps), abs_tol=1e-8): + return default + return value + + def project_session_state( recipe: inlayer_project.Project, figure_ids: list[str] ) -> tuple[dict[str, object], dict[str, dict[str, float]]]: - """Session values for a recipe, rejecting values the widgets would alter. + """Map a validated recipe to exact values and separate editable controls. - Upload ids are only the targets of this one-time mapping. The recipe's own - persistent ids stay in the project and are never derived from Streamlit. + Config and per-figure values stay independent of the controls' ranges and + steps. Only an explicit edit replaces a corresponding imported value. + Upload ids are transient targets; persistent ids stay in the recipe. """ if len(figure_ids) != len(recipe.figures): raise inlayer_project.ProjectError(t("project.invalid_field", field="figures")) - def unsupported(field: str): - raise inlayer_project.ProjectError(t("project.web_value", field=field)) - - def ranged(field: str, value: float, lo: float, hi: float) -> float: - if not lo <= value <= hi: - unsupported(field) - return value - - def slider(field: str, value: float, lo: float, hi: float, step: float) -> float: - ranged(field, value, lo, hi) - steps = (value - lo) / step - if not math.isclose(steps, round(steps), abs_tol=1e-8): - unsupported(field) - return round(lo + round(steps) * step, 10) - - def integer(field: str, value: float, lo: float, hi: float) -> float: - ranged(field, value, lo, hi) - if not math.isclose(value, round(value), abs_tol=1e-8): - unsupported(field) - return float(round(value)) - config = recipe.config box_fields = ("box_diameter", "box_height") if config.box_shape == "cylinder" else ( "box_width", "box_depth", "box_height", ) - use_custom_box = any(getattr(config, field) is not None for field in box_fields) - if use_custom_box: - for field in box_fields: - if getattr(config, field) is None: - unsupported(field) - gap = config.wall_thickness if config.figure_gap is None else slider( - "figure_gap", config.figure_gap, 0.5, 40.0, 0.5 - ) + gap = project_widget_value(config.effective_figure_gap, 2.0, 0.5, 40.0, 0.5) values: dict[str, object] = { - "clearance": slider("clearance", config.clearance, 0.1, 2.0, 0.1), - "wall_thickness": slider("wall_thickness", config.wall_thickness, 1.0, 5.0, 0.5), - "depth_fraction": slider("depth_fraction", config.depth_fraction, 0.3, 1.0, 0.05), - "voxel_pitch": slider("voxel_pitch", config.voxel_pitch, 0.2, 1.0, 0.1), - "decimate_faces": ranged("decimate_faces", config.decimate_faces, 5000, 50000), - "scale": ranged("stl_unit_to_mm", config.stl_unit_to_mm, 0.01, 100.0), + "_project_config_base": config, + "_project_config_edits": {}, + "_project_exact_figure_fields": { + fid: set(FIGURE_DEFAULTS) for fid in figure_ids + }, + "clearance": project_widget_value(config.clearance, inlayer.Config.clearance, 0.1, 2.0, 0.1), + "wall_thickness": project_widget_value(config.wall_thickness, inlayer.Config.wall_thickness, 1.0, 5.0, 0.5), + "depth_fraction": project_widget_value(config.depth_fraction, inlayer.Config.depth_fraction, 0.3, 1.0, 0.05), + "voxel_pitch": project_widget_value(config.voxel_pitch, inlayer.Config.voxel_pitch, 0.2, 1.0, 0.1), + "decimate_faces": project_widget_value(config.decimate_faces, inlayer.Config.decimate_faces, 5000, 50000), + "scale": project_widget_value(config.stl_unit_to_mm, inlayer.Config.stl_unit_to_mm, 0.01, 100.0), "finger_enabled": config.enable_finger_recesses, "finger_axis": config.finger_recess_axis, "_w_finger_axis": config.finger_recess_axis, "parallel": config.enable_parallel, "box_shape": config.box_shape, "_w_box_shape": config.box_shape, - "use_custom_box": use_custom_box, + "use_custom_box": any(getattr(config, field) is not None for field in box_fields), "manual_offsets": any( - not math.isclose(value, 0.0, abs_tol=1e-12) - for offset in inlayer_project.effective_offsets(recipe) for value in offset - ), - "manual_rotations": any( - not math.isclose(value % 360.0, 0.0, abs_tol=1e-12) - for figure in recipe.figures for value in figure.rotation - ), + value != 0.0 for value in (config.offset_x, config.offset_y, config.offset_z) + ) or any(value != 0.0 for figure in recipe.figures for value in figure.offset), + "manual_rotations": any(value != 0.0 for figure in recipe.figures for value in figure.rotation), "pos_step": 1.0, "rot_step": 1.0, "_w_pos_step": 1.0, @@ -208,40 +197,24 @@ def integer(field: str, value: float, lo: float, hi: float) -> float: "_ni_figure_gap": gap, "_gap_user_set": config.figure_gap is not None, } - for key, field, value, lo, hi in ( - ("finger_radius", "finger_radius", config.finger_radius, 5.0, 15.0), - ("finger_z_offset", "finger_recess_z_offset", config.finger_recess_z_offset, 0.0, 30.0), + for key, value, default, lo, hi in ( + ("finger_radius", config.finger_radius, inlayer.Config.finger_radius, 5.0, 15.0), + ("finger_z_offset", config.finger_recess_z_offset, inlayer.Config.finger_recess_z_offset, 0.0, 30.0), + ("box_width", config.box_width, 50.0, 10.0, 300.0), + ("box_depth", config.box_depth, 50.0, 10.0, 300.0), + ("box_height", config.box_height, 20.0, 5.0, 200.0), + ("box_diameter", config.box_diameter, 50.0, 10.0, 300.0), ): - step = 0.5 - values[key] = slider(field, value, lo, hi, step) + step = 0.5 if key.startswith("finger_") else None + values[key] = project_widget_value(value, default, lo, hi, step) values[f"_{key}_value"] = values[key] - for key, field, value, default, lo, hi in ( - ("box_width", "box_width", config.box_width, 50.0, 10.0, 300.0), - ("box_depth", "box_depth", config.box_depth, 50.0, 10.0, 300.0), - ("box_height", "box_height", config.box_height, 20.0, 5.0, 200.0), - ("box_diameter", "box_diameter", config.box_diameter, 50.0, 10.0, 300.0), - ): - checked = default if value is None else ranged(field, value, lo, hi) - values[key] = checked - values[f"_{key}_value"] = checked stored = {} - effective = inlayer_project.effective_offsets(recipe) - for figure, upload_id, offset in zip(recipe.figures, figure_ids, effective): - rotation = [integer(f"rotation[{i}]", value % 360.0, 0.0, 359.0) - for i, value in enumerate(figure.rotation)] - offset = [ - integer(f"offset_{axis}", value, limits[0], limits[1]) - for axis, value, limits in zip("xyz", offset, ((-100, 100), (-100, 100), (-50, 150))) - ] - percent = figure.finger_recess_position * 100.0 - if not math.isclose(percent / 5.0, round(percent / 5.0), rel_tol=0.0, abs_tol=1e-8): - unsupported("finger_recess_position") + for figure, upload_id in zip(recipe.figures, figure_ids): stored[upload_id] = { - **dict(FIGURE_DEFAULTS), - **dict(zip(OFFSET_AXES, offset)), - **dict(zip(ROTATION_AXES, rotation)), - "finger_recess_position": round(percent) / 100.0, + **dict(zip(OFFSET_AXES, figure.offset)), + **dict(zip(ROTATION_AXES, figure.rotation)), + "finger_recess_position": figure.finger_recess_position, } for selection in ("selected_recess_fig", "selected_fig", "selected_rot_fig"): values[f"_ref_{selection}"] = None diff --git a/i18n.py b/i18n.py index 736a1d5..52d52f0 100644 --- a/i18n.py +++ b/i18n.py @@ -159,6 +159,10 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Projekt geladen: {n} Figuren und ihre Quellen wurden per SHA-256 geprüft.", "en": "Project loaded: {n} figures and their sources were verified by SHA-256.", }, + "app.project.controls": { + "de": "Importierte Werte bleiben für Berechnung und Export exakt erhalten, auch automatische Maße. Regler können einen abweichenden bearbeitbaren Wert anzeigen; erst eine bewusste Änderung ersetzt den zugehörigen Projektwert.", + "en": "Imported values stay exact for generation and export, including automatic dimensions. Controls may show a different editable value; only an explicit edit replaces the corresponding project value.", + }, "app.project.heading": { "de": "### 💾 Projekt", "en": "### 💾 Project", @@ -168,8 +172,8 @@ def t(key: str, /, **kwargs: object) -> str: "en": "Download project as JSON", }, "app.project.download.help": { - "de": "Speichert Formatversion 1 mit Konfiguration, vollständigen SHA-256-Quellhashes, stabilen Figuren-IDs sowie individuellen Rotationen, Offsets und Griffpositionen. Deaktivierte individuelle Funktionen werden mit ihren wirksamen Nullwerten gespeichert. STLs werden nicht eingebettet.", - "en": "Saves format version 1 with configuration, full SHA-256 source hashes, stable figure ids and individual rotations, offsets and grip positions. Disabled individual features are saved with their effective zero values. STLs are not embedded.", + "de": "Speichert Formatversion 1 mit Konfiguration, vollständigen SHA-256-Quellhashes, stabilen Figuren-IDs sowie individuellen Rotationen, Offsets und Griffpositionen. Importierte Griffparameter bleiben auch bei deaktivierten Fingermulden erhalten. STLs werden nicht eingebettet.", + "en": "Saves format version 1 with configuration, full SHA-256 source hashes, stable figure ids and individual rotations, offsets and grip positions. Imported grip settings are retained while finger recesses are disabled. STLs are not embedded.", }, # --- Sidebar: Druckeinstellungen --------------------------------------- "app.printer.heading": { @@ -853,7 +857,7 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Die Figur", "en": "The figure", }, - # --- Versionierte Projektdateien ----------------------------------------- + # --- Versioned project files --------------------------------------------- "project.invalid_json": { "de": "Die Projektdatei ist kein gültiges UTF-8-JSON.", "en": "The project file is not valid UTF-8 JSON.", @@ -898,10 +902,6 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Quelldatei für '{name}' wurde seit dem Export verändert: {path}", "en": "Source file for '{name}' has changed since the project was exported: {path}", }, - "project.web_value": { - "de": "Der Wert von '{field}' kann in der Weboberfläche nicht verlustfrei dargestellt werden. Das Projekt wurde nicht verändert; nutze die CLI oder passe das Rezept an.", - "en": "The value of '{field}' cannot be represented losslessly in the web app. The project was not changed; use the CLI or adjust the recipe.", - }, # --- CLI ---------------------------------------------------------------- "cli.description": { "de": "Inlayer: Erstellt 3D-druckbare Verpackungseinleger für Figuren.", diff --git a/tests/test_app_helpers.py b/tests/test_app_helpers.py index 59321c7..d6e0c94 100644 --- a/tests/test_app_helpers.py +++ b/tests/test_app_helpers.py @@ -109,7 +109,7 @@ def test_same_named_sources_map_to_upload_ids_only_once(self): assert not {"persistent-one", "persistent-two"} & set(stored) first = stored["temporary-upload-b"] second = stored["temporary-upload-a"] - assert (first["rot_x"], first["rot_y"], first["rot_z"]) == (10.0, 45.0, 0.0) + assert (first["rot_x"], first["rot_y"], first["rot_z"]) == (370.0, 45.0, 0.0) assert (second["rot_x"], second["rot_y"], second["rot_z"]) == (0.0, 0.0, 90.0) assert (first["offset_x"], first["offset_y"], first["offset_z"]) == (1.0, 2.0, 3.0) assert (second["offset_x"], second["offset_y"], second["offset_z"]) == (-1.0, 0.0, 4.0) @@ -119,14 +119,19 @@ def test_same_named_sources_map_to_upload_ids_only_once(self): assert values["manual_rotations"] is True assert values["figure_gap"] == values["_sl_figure_gap"] == 2.0 - def test_global_and_individual_offsets_are_combined_for_the_widgets(self): + def test_global_and_individual_offsets_stay_separate_until_application(self): recipe = self._recipe() recipe = replace(recipe, config=replace( recipe.config, offset_x=2.0, offset_y=-1.0, offset_z=1.0, )) - _, stored = app_helpers.project_session_state(recipe, ["first", "second"]) - assert [stored["first"][f"offset_{axis}"] for axis in "xyz"] == [3.0, 1.0, 4.0] - assert [stored["second"][f"offset_{axis}"] for axis in "xyz"] == [1.0, -1.0, 5.0] + values, stored = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["_project_config_base"] == recipe.config + assert [stored["first"][f"offset_{axis}"] for axis in "xyz"] == [1.0, 2.0, 3.0] + assert [stored["second"][f"offset_{axis}"] for axis in "xyz"] == [-1.0, 0.0, 4.0] + applied = app_helpers.applied_figure_params( + stored, ["first", "second"], True, True, True, (2.0, -1.0, 1.0), + ) + assert [figure["offset"] for figure in applied] == [(3.0, 1.0, 4.0), (1.0, -1.0, 5.0)] @pytest.mark.parametrize("shape,dimensions", [ ("box", {"box_height": 30.0}), @@ -135,11 +140,13 @@ def test_global_and_individual_offsets_are_combined_for_the_widgets(self): ("cylinder", {"box_height": 30.0}), ("cylinder", {"box_diameter": 60.0}), ]) - def test_partial_active_box_dimensions_are_rejected(self, shape, dimensions): + def test_partial_active_box_dimensions_preserve_automatic_fields(self, shape, dimensions): recipe = self._recipe() recipe = replace(recipe, config=replace(recipe.config, box_shape=shape, **dimensions)) - with pytest.raises(inlayer_project.ProjectError, match="box_"): - app_helpers.project_session_state(recipe, ["first", "second"]) + values, _ = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["_project_config_base"] == recipe.config + assert values["use_custom_box"] is True + assert recipe.config.figure_gap is None @pytest.mark.parametrize("shape,dimensions", [ ("box", {"box_diameter": 80.0}), @@ -169,7 +176,7 @@ def test_complete_active_box_dimensions_are_preserved(self, shape, dimensions): ("offset", 0.5), ("finger_recess_position", 0.12), ]) - def test_values_the_widgets_would_change_are_rejected(self, field, value): + def test_values_outside_the_widget_palette_are_preserved_exactly(self, field, value): recipe = self._recipe() if field in inlayer.Config.__dataclass_fields__ and field != "finger_recess_position": recipe = replace(recipe, config=replace(recipe.config, **{field: value})) @@ -179,9 +186,37 @@ def test_values_the_widgets_would_change_are_rejected(self, field, value): field: (value, *getattr(first, field)[1:]), } recipe = replace(recipe, figures=(replace(first, **changed), *recipe.figures[1:])) - with pytest.raises(inlayer_project.ProjectError) as error: - app_helpers.project_session_state(recipe, ["first", "second"]) - assert field.split("_")[0] in str(error.value) + values, stored = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["_project_config_base"] == recipe.config + assert stored["first"]["rot_x"] == recipe.figures[0].rotation[0] + assert stored["first"]["offset_x"] == recipe.figures[0].offset[0] + assert stored["first"]["finger_recess_position"] == recipe.figures[0].finger_recess_position + assert values["_project_config_edits"] == {} + exact_fields = values["_project_exact_figure_fields"] + assert isinstance(exact_fields, dict) + assert exact_fields["first"] == set(app_helpers.FIGURE_DEFAULTS) + + def test_extreme_valid_values_never_enter_widget_state(self): + recipe = self._recipe() + recipe = replace(recipe, config=replace( + recipe.config, decimate_faces=10 ** 400, stl_unit_to_mm=1e308, + clearance=1e308, figure_gap=1e308, + ), figures=(replace(recipe.figures[0], rotation=(1e308, -1e308, 12.5), + offset=(1e308, -1e308, 0.5)), recipe.figures[1])) + values, stored = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["_project_config_base"] == recipe.config + assert values["decimate_faces"] == inlayer.Config.decimate_faces + assert values["scale"] == inlayer.Config.stl_unit_to_mm + assert stored["first"]["rot_x"] == 1e308 + assert stored["first"]["offset_y"] == -1e308 + + def test_cancelling_global_and_individual_offsets_keep_the_feature_enabled(self): + recipe = self._recipe() + recipe = replace(recipe, config=replace(recipe.config, offset_x=1.0), figures=tuple( + replace(figure, offset=(-1.0, 0.0, 0.0)) for figure in recipe.figures + )) + values, _ = app_helpers.project_session_state(recipe, ["first", "second"]) + assert values["manual_offsets"] is True class TestPreviewCopy: diff --git a/tests/test_app_render.py b/tests/test_app_render.py index 07e09cd..804fae3 100644 --- a/tests/test_app_render.py +++ b/tests/test_app_render.py @@ -1,11 +1,8 @@ -"""Rendert die Streamlit-App in beiden Sprachen. - -`app.py` liess sich lange nicht testen, weil es `st.set_page_config()` aufruft -und die Sidebar auf Modul-Ebene baut — deshalb liegt die pure Logik in -`app_helpers.py`. Streamlits `AppTest` fuehrt das Skript aber in einer echten -Laufzeitumgebung aus und macht damit genau das pruefbar, was dort nicht -hinauswandern kann: dass die Oberflaeche ueberhaupt fehlerfrei durchlaeuft und -dass die Sprachumschaltung die Beschriftungen erreicht. +"""Render the Streamlit app in both languages. + +The pure logic lives in `app_helpers.py` because importing `app.py` configures +the page and builds the sidebar. AppTest runs the actual script in a Streamlit +runtime to check rendering, interaction, and translated labels. """ from __future__ import annotations @@ -14,6 +11,7 @@ import base64 import io import json +from dataclasses import replace from pathlib import Path from typing import cast @@ -856,6 +854,81 @@ def test_automatic_gap_keeps_following_wall_thickness_after_reopening(self): restarted.session_state["_project_export"] ).config.figure_gap is None + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_single_source_preserves_hidden_and_inactive_values_when_editing(self, lang): + """One visible edit must retain imported values that have no visible control.""" + files = [self._files()[0]] + config = inlayer.Config( + clearance=0.25, voxel_pitch=1.0, decimate_faces=1000, + box_height=30.0, box_diameter=77.25, figure_gap=7.25, + layout_style="vertical", offset_x=0.5, offset_z=0.25, + finger_recess_position=0.37, enable_finger_recesses=False, + finger_radius=4.25, finger_recess_z_offset=0.25, + ) + recipe = inlayer_project.new_project( + config, + [inlayer_project.SourceIdentity("model.stl", inlayer_project.bytes_hash(files[0][1]))], + rotations=[(-12.5, 372.5, 720.0)], offsets=[(0.5, 0.0, 0.25)], + recess_positions=[0.12], figure_ids=["persistent-figure"], + ) + at = _open_project(_run(lang), files, inlayer_project.dumps_project(recipe)) + assert not at.error + assert inlayer_project.loads_project(at.session_state["_project_export"]) == recipe + _widget(at, "selectbox", "ui_lang").set_value("de" if lang == "en" else "en").run() + assert not at.exception and not at.error + assert inlayer_project.loads_project(at.session_state["_project_export"]) == recipe + _widget(at, "slider", "clearance").set_value(0.6).run() + assert not at.exception and not at.error + assert inlayer_project.loads_project(at.session_state["_project_export"]) == replace( + recipe, config=replace(config, clearance=0.6), + ) + + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + @pytest.mark.parametrize("action", ["hide_radius", "switch_shape", "cancel_offset", "toggle_axes"]) + def test_imported_values_survive_hiding_controls_and_toggling_features(self, lang, action): + """Hidden widgets must not undo edits or discard untouched recipe values.""" + files = [self._files()[0]] + config = inlayer.Config( + clearance=0.25, voxel_pitch=1.0, decimate_faces=1000, + box_width=50.0, box_height=30.0, offset_x=0.5, + enable_finger_recesses=True, finger_radius=5.0, + ) + recipe = inlayer_project.new_project( + config, + [inlayer_project.SourceIdentity("model.stl", inlayer_project.bytes_hash(files[0][1]))], + rotations=[(0.0, 0.0, 12.5)], + offsets=[(-0.5 if action == "cancel_offset" else 0.5, 0.0, 0.0)], + recess_positions=[0.12], figure_ids=["persistent-figure"], + ) + at = _open_project(_run(lang), files, inlayer_project.dumps_project(recipe)) + assert not at.error + expected = recipe + if action == "hide_radius": + _widget(at, "slider", "finger_radius").set_value(6.5).run() + _widget(at, "checkbox", "finger_enabled").uncheck().run() + expected = replace(recipe, config=replace(config, finger_radius=6.5, + enable_finger_recesses=False)) + elif action == "switch_shape": + _widget(at, "number_input", "box_width").set_value(60.0).run() + _widget(at, "selectbox", "_w_box_shape").set_value("cylinder").run() + expected = replace(recipe, config=replace(config, box_width=60.0, box_shape="cylinder")) + elif action == "toggle_axes": + _widget(at, "checkbox", "manual_offsets").uncheck().run() + _widget(at, "checkbox", "manual_rotations").uncheck().run() + disabled = inlayer_project.loads_project(at.session_state["_project_export"]) + assert disabled == replace( + recipe, config=replace(config, offset_x=0.0), + figures=(replace(recipe.figures[0], offset=(0.0, 0.0, 0.0), + rotation=(0.0, 0.0, 0.0)),), + ) + _widget(at, "checkbox", "manual_offsets").check().run() + _widget(at, "checkbox", "manual_rotations").check().run() + assert not at.exception and not at.error + assert inlayer_project.loads_project(at.session_state["_project_export"]) == expected + _widget(at, "selectbox", "ui_lang").set_value("de" if lang == "en" else "en").run() + assert not at.exception and not at.error + assert inlayer_project.loads_project(at.session_state["_project_export"]) == expected + def test_fresh_web_session_reproduces_geometry_and_wall_findings(self): files = self._files() original = _open_project(_run("en"), files, _project_recipe(files)) @@ -890,7 +963,7 @@ def measured(result): np.testing.assert_allclose(reopened_mesh.bounds, original_mesh.bounds, atol=2e-3) @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) - @pytest.mark.parametrize("case", ["missing", "changed", "version", "web_value", "partial_box"]) + @pytest.mark.parametrize("case", ["missing", "changed", "version", "invalid_value"]) def test_invalid_project_or_source_stops_before_the_pipeline(self, lang, case, monkeypatch): files = self._files() recipe = _project_recipe(files) @@ -912,16 +985,13 @@ def test_invalid_project_or_source_stops_before_the_pipeline(self, lang, case, m raw["version"] = 99 recipe = json.dumps(raw) expected = i18n.TRANSLATIONS["project.unsupported_version"][lang].format(version=99) - elif case == "web_value": - raw = json.loads(recipe) - raw["config"]["clearance"] = 0.25 - recipe = json.dumps(raw) - expected = i18n.TRANSLATIONS["project.web_value"][lang].format(field="clearance") else: raw = json.loads(recipe) - raw["config"]["box_height"] = 30.0 + raw["config"]["clearance"] = -0.25 recipe = json.dumps(raw) - expected = i18n.TRANSLATIONS["project.web_value"][lang].format(field="box_width") + expected = i18n.TRANSLATIONS["config.must_be_non_negative"][lang].format( + name="clearance", value=-0.25, + ) def pipeline_must_not_start(*_args, **_kwargs): raise AssertionError("the pipeline must not start") diff --git a/tests/test_project.py b/tests/test_project.py index e65b763..b0aa6c5 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -3,10 +3,12 @@ from __future__ import annotations import json +import io import subprocess import sys import uuid -from dataclasses import replace +from dataclasses import asdict, replace +from pathlib import Path import numpy as np import pytest @@ -83,6 +85,99 @@ def _project(tmp_path, with_paths=True): return recipe, (first, second, paths) +def _observed_cli(args, cwd, report_path): + """Run the real CLI in a fresh process, recording its pipeline boundary.""" + script = """ +import json +import sys +from dataclasses import asdict +from pathlib import Path +sys.path.insert(0, sys.argv.pop(1)) +report_path = Path(sys.argv.pop(1)) +import inlayer +report = {} +real_build = inlayer.build_inlay +real_stats = inlayer.wall_thickness_stats_3d +def build(figures, config, **kwargs): + report['config'] = asdict(config) + report['offsets'] = kwargs.get('individual_offsets') + if report['offsets'] is None: + report['offsets'] = [(config.offset_x, config.offset_y, config.offset_z)] * len(figures) + report['grips'] = kwargs.get('individual_recess_positions') + report['figure_bounds'] = [mesh.bounds.tolist() for mesh in figures] + return real_build(figures, config, **kwargs) +def stats(mesh): + report['stats'] = real_stats(mesh) + return report['stats'] +inlayer.build_inlay = build +inlayer.wall_thickness_stats_3d = stats +code = inlayer.main(sys.argv[1:]) +report_path.write_text(json.dumps(report), encoding='utf-8') +raise SystemExit(code) +""" + result = subprocess.run( + [sys.executable, "-c", script, str(Path(inlayer.__file__).parent), str(report_path), + *map(str, args)], + cwd=cwd, capture_output=True, text=True, timeout=120, + ) + assert result.returncode in (0, inlayer.EXIT_CHECK_FAILED), result.stdout + result.stderr + return result, json.loads(report_path.read_text(encoding="utf-8")) + + +def _assert_project_values(actual, expected): + """The Web omits local paths, but must preserve every recipe value.""" + assert actual.config == expected.config + assert actual.figures == tuple( + replace(figure, source=replace(figure.source, path=None)) for figure in expected.figures + ) + + +def _assert_same_finished_mesh(actual, expected, shape): + """Measure exported meshes independently of pipeline metadata.""" + from tests import geometry_probe as probe + + np.testing.assert_allclose(actual.bounds, expected.bounds, atol=2e-3) + assert actual.volume == pytest.approx(expected.volume, rel=1e-5, abs=2e-3) + assert probe.shell_count(actual) == probe.shell_count(expected) == 1 + dimensions = expected.extents + if shape == "box": + assert probe.outer_walls(actual, *dimensions) == pytest.approx( + probe.outer_walls(expected, *dimensions), abs=2e-3, + ) + assert probe.inner_gap(actual, *dimensions) == pytest.approx( + probe.inner_gap(expected, *dimensions), abs=2e-3, + ) + pockets = probe.cavities(actual, *dimensions) + reference_pockets = probe.cavities(expected, *dimensions) + else: + assert probe.cylinder_side_wall(actual) == pytest.approx( + probe.cylinder_side_wall(expected), abs=2e-3, + ) + # The finished mesh's convex hull closes the pockets independently of + # the pipeline's cylinder dimensions or polygon construction. + def cylinder_pockets(mesh): + removed = probe.to_manifold(mesh.convex_hull) - probe.to_manifold(mesh) + return [p for p in removed.decompose() if p.volume() > 1e-3] + + pockets = cylinder_pockets(actual) + reference_pockets = cylinder_pockets(expected) + assert pockets[0].min_gap(pockets[1], 5.0) == pytest.approx( + reference_pockets[0].min_gap(reference_pockets[1], 5.0), abs=2e-3, + ) + assert len(pockets) == len(reference_pockets) == 2 + np.testing.assert_allclose( + sorted(p.volume() for p in pockets), sorted(p.volume() for p in reference_pockets), + atol=2e-3, + ) + np.testing.assert_allclose( + sorted(tuple(p.bounding_box()) for p in pockets), + sorted(tuple(p.bounding_box()) for p in reference_pockets), atol=2e-3, + ) + actual_solid, expected_solid = probe.to_manifold(actual), probe.to_manifold(expected) + assert (actual_solid - expected_solid).volume() < 2e-3 + assert (expected_solid - actual_solid).volume() < 2e-3 + + class TestRoundTrip: def test_config_sources_and_individual_settings_survive(self, tmp_path): recipe, _ = _project(tmp_path) @@ -319,6 +414,142 @@ def _signature(path): assert isinstance(mesh, trimesh.Trimesh) return np.concatenate([mesh.extents, [mesh.volume], mesh.center_mass]) + @pytest.mark.slow + @pytest.mark.parametrize("case,changes", [ + pytest.param("cli-height", {}, id="cli-flags-partial-box-height"), + pytest.param("recipe", {"box_width": 60.0}, id="partial-box-width"), + pytest.param("recipe", {"box_depth": 35.0}, id="partial-box-depth"), + pytest.param("recipe", {"box_shape": "cylinder", "box_height": 30.0}, + id="partial-cylinder-height"), + pytest.param("recipe", {"box_shape": "cylinder", "box_diameter": 60.0}, + id="partial-cylinder-diameter"), + pytest.param("recipe", { + "clearance": 0.25, "decimate_faces": 1000, "wall_thickness": 2.25, + "depth_fraction": 0.725, "voxel_pitch": 0.75, "stl_unit_to_mm": 1.025, + "finger_radius": 5.25, "finger_recess_z_offset": 0.25, + }, id="fractional-values"), + pytest.param("recipe", { + "clearance": 2.25, "wall_thickness": 6.0, "depth_fraction": 0.25, + "voxel_pitch": 1.25, "decimate_faces": 1000, "finger_radius": 4.25, + "finger_recess_z_offset": 30.5, "figure_gap": 40.5, + "box_width": 301.0, "box_height": 50.0, "offset_x": 100.5, + }, id="outside-widget-ranges"), + pytest.param("recipe", {"enable_finger_recesses": False}, + id="disabled-recess-values"), + ]) + def test_cli_web_cli_preserves_and_applies_every_recipe_value( + self, tmp_path, monkeypatch, case, changes, + ): + """CLI exports survive fresh Web sessions and another CLI process unchanged.""" + from tests.test_app_render import _open_project, _run, _widget + + first, second, paths, sources = _sources(tmp_path) + initial_json = tmp_path / "initial.json" + initial_stl = tmp_path / "initial.stl" + if case == "cli-height": + # Reproduce the reported valid CLI invocation with automatic width/depth. + original, original_report = _observed_cli([ + "-i", *paths, "--box-height", "30", "--voxel-pitch", "1", + "--decimate-faces", "5000", "--save-project", initial_json, + "-o", initial_stl, + ], tmp_path, tmp_path / "initial-report.json") + else: + config = replace( + _config(), figure_gap=None, offset_x=0.5, offset_z=0.25, + finger_recess_position=0.37, + ) + config = replace(config, **changes) + recipe = new_project( + config, sources, + rotations=[(-12.5, 0.0, 372.5), (0.0, 720.0, 12.5)], + offsets=[(0.5, 0.0, 0.25), (-0.5, 0.5, 0.0)], + recess_positions=[0.12, -0.12], + figure_ids=["figure-one", "figure-two"], project_path=initial_json, + ) + save_project(recipe, initial_json) + original, original_report = _observed_cli([ + "--project", initial_json, "-i", *paths, "-o", initial_stl, + "--save-project", tmp_path / "cli-export.json", + ], tmp_path, tmp_path / "initial-report.json") + initial_json = tmp_path / "cli-export.json" + expected = load_project(initial_json) + assert original_report["config"] == asdict(expected.config) + assert expected.config.figure_gap is None or changes.get("figure_gap") == 40.5 + if case == "cli-height": + assert (expected.config.box_width, expected.config.box_depth) == (None, None) + assert expected.config.box_height == 30.0 + + observed = [] + real_build = inlayer.build_inlay + + def capture_build(figures, config, **kwargs): + observed.append((config, kwargs, [mesh.bounds.copy() for mesh in figures])) + return real_build(figures, config, **kwargs) + + monkeypatch.setattr(inlayer, "build_inlay", capture_build) + files = [("model.stl", second), ("model.stl", first)] + web = _open_project(_run("en"), files, initial_json.read_text(encoding="utf-8")) + assert not web.error, [error.value for error in web.error] + _assert_project_values(loads_project(web.session_state["_project_export"]), expected) + # A language switch must not turn widget projections into recipe edits. + _widget(web, "selectbox", "ui_lang").set_value("de").run() + assert not web.exception and not web.error + _assert_project_values(loads_project(web.session_state["_project_export"]), expected) + if changes.get("clearance") == 0.25: + uploads_by_project = { + project_id: upload_id + for upload_id, project_id in web.session_state["_project_id_by_file_id"].items() + } + for key in ("selected_fig", "selected_rot_fig", "selected_recess_fig"): + for figure in reversed(expected.figures): + _widget(web, "selectbox", key).set_value(uploads_by_project[figure.id]).run() + assert not web.exception and not web.error + _assert_project_values( + loads_project(web.session_state["_project_export"]), expected, + ) + web.button[0].click().run() + assert not web.exception and not web.error + assert len(observed) == 1 + passed_config, kwargs, figure_bounds = observed[0] + assert passed_config == expected.config + assert kwargs["individual_offsets"] == effective_offsets(expected) + if expected.config.enable_finger_recesses: + assert kwargs["individual_recess_positions"] == [ + figure.finger_recess_position for figure in expected.figures + ] + np.testing.assert_allclose( + figure_bounds, original_report["figure_bounds"], atol=2e-3, + ) + result = web.session_state["result"] + assert result["stats_3d"] == original_report["stats"] + actual = loads_project(web.session_state["_project_export"]) + _assert_project_values(actual, expected) + assert [figure.source.sha256 for figure in actual.figures] == [ + project_module.bytes_hash(first), project_module.bytes_hash(second), + ] + assert all(len(figure.source.sha256) == 64 for figure in actual.figures) + + web_json = tmp_path / "web.json" + web_json.write_text(web.session_state["_project_export"], encoding="utf-8") + elsewhere = tmp_path / "other-cwd" + elsewhere.mkdir() + reopened_stl = tmp_path / "reopened.stl" + reopened, reopened_report = _observed_cli([ + "--project", web_json, "-i", *reversed(paths), "-o", reopened_stl, + "--save-project", tmp_path / "reopened.json", + ], elsewhere, tmp_path / "reopened-report.json") + assert reopened.returncode == original.returncode + assert reopened_report == original_report + reopened_recipe = load_project(tmp_path / "reopened.json") + assert reopened_recipe == expected + web_mesh = trimesh.load(io.BytesIO(result["stl_bytes"]), file_type="stl", force="mesh") + original_mesh = trimesh.load(str(initial_stl), force="mesh") + reopened_mesh = trimesh.load(str(reopened_stl), force="mesh") + assert all(isinstance(mesh, trimesh.Trimesh) + for mesh in (web_mesh, original_mesh, reopened_mesh)) + _assert_same_finished_mesh(web_mesh, original_mesh, expected.config.box_shape) + _assert_same_finished_mesh(reopened_mesh, original_mesh, expected.config.box_shape) + def test_restart_reopens_same_named_sources_and_individual_settings( self, tmp_path, capsys, monkeypatch ):