Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 26 additions & 26 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,6 @@ def _mesh3d(mesh: trimesh.Trimesh, **kwargs) -> go.Mesh3d:
)


_scene_layout = app_helpers.scene_layout


# --- Logger -----------------------------------------------------------------
class StreamlitLogger:
def __init__(self, status_container):
Expand Down Expand Up @@ -690,6 +687,7 @@ def _params_snapshot() -> dict:

# --- Pipeline ---------------------------------------------------------------
if run_btn:
st.session_state.pop("result", None)
tmp_paths: list[str] = []
try:
# Input: the uploads, or the default file next to the app
Expand All @@ -711,7 +709,7 @@ def _params_snapshot() -> dict:
input_paths.append(tmp_paths[-1])
file_names.append(_labels[uf.file_id])
file_hashes.append(content_hashes[uf.file_id])
elif os.path.exists(fallback_path):
elif os.path.isfile(fallback_path):
input_paths = [fallback_path]
file_names = [fallback_path]
file_hashes = [app_helpers.file_hash(fallback_path)]
Expand Down Expand Up @@ -819,6 +817,10 @@ def _prepare_one(i: int):
# Only what the result view reads, as geometry-only copies: the full
# inlay (and before that the dilated figures) sat in every session's
# state although the view needs a decimated mesh and a few numbers.
# Everything that determines a prepared, rotated figure goes into its
# cache key: two figures on the same round base cut the same inlay, so
# the inlay's hash alone would draw the other session's figure.
max_fig_faces = 15000 if not is_multi else 10000
st.session_state["result"] = {
"params": _params_snapshot(),
"stats_3d": stats_3d,
Expand All @@ -835,20 +837,20 @@ def _prepare_one(i: int):
app_helpers.preview_copy(r, INLAY_PREVIEW_FACES)
for r in inlay.metadata.get("finger_recesses", [])
],
"fig_meshes": fig_meshes,
# Everything that determines a prepared, rotated figure. The inlay's
# hash does not: two figures on the same round base cut the same
# inlay, and the preview then drew the other session's figure.
"fig_cache_keys": [
f"{file_hashes[i]}:{scale}:{voxel_pitch}:{decimate_faces}:"
+ ":".join(str(r) for r in rotations[i])
"fig_viz": [
_decimated_for_viz(
fig_meshes[i],
f"{file_hashes[i]}:{scale}:{voxel_pitch}:{decimate_faces}:"
+ ":".join(str(r) for r in rotations[i]),
max_fig_faces,
)
for i in range(n_files)
],
"file_names": file_names,
"is_multi": is_multi,
}

except (ValueError, RuntimeError, MemoryError) as e:
except (ValueError, RuntimeError, OSError, MemoryError) as e:
# Raised on purpose, with a message written for the user: an unusable
# upload, a grid beyond the limit, a box that leaves no material.
reason = t("error.out_of_memory") if isinstance(e, MemoryError) else e
Expand Down Expand Up @@ -877,7 +879,6 @@ def _prepare_one(i: int):
actual_h = res["actual_h"]
stl_bytes = res["stl_bytes"]
_wt = res["wall_thickness"]
fig_meshes = res["fig_meshes"]
_file_names = res["file_names"]
_is_multi = res["is_multi"]

Expand Down Expand Up @@ -963,20 +964,15 @@ def _prepare_one(i: int):
name=t("app.trace.inlay"), showlegend=True,
))

# One colour per figure
max_fig_faces = 15000 if not _is_multi else 10000
# Exactly the translation build_inlay applied to each figure. The
# prepared figure shares its frame with the dilated one it was given,
# so the same translation puts it inside its cavity.
for i, fig_m in enumerate(fig_meshes):
viz_fig = _decimated_for_viz(fig_m, res["fig_cache_keys"][i], max_fig_faces).copy()
# One colour per figure. Exactly the translation build_inlay applied to
# each figure puts the prepared figure inside its cavity.
for i, viz_m in enumerate(res["fig_viz"]):
viz_fig = viz_m.copy()
viz_fig.apply_translation(res["placements"][i])

color = _fig_colors[i % len(_fig_colors)]
label = (_file_names[i] if i < len(_file_names)
else t("app.trace.figure", i=i + 1))
if _is_multi:
label = t("app.trace.figure_named", i=i + 1, name=label)
label = (t("app.trace.figure_named", i=i + 1, name=_file_names[i])
if _is_multi else _file_names[i])

fig_3d.add_trace(_mesh3d(
viz_fig, color=color, opacity=0.6, name=label, showlegend=True,
Expand All @@ -988,10 +984,14 @@ def _prepare_one(i: int):
name=t("app.trace.recesses"), showlegend=(r_idx == 0),
))

fig_3d.update_layout(**_scene_layout(650))
fig_3d.update_layout(**app_helpers.scene_layout(650))
st.plotly_chart(fig_3d, width="stretch")
st.info(t("app.viewer.hint"))

elif len(uploaded_files) > app_helpers.MAX_UPLOAD_FILES:
st.error(t("app.error.too_many_files", n=len(uploaded_files),
limit=app_helpers.MAX_UPLOAD_FILES))

elif uploaded_files:
# --- Instant preview: the figures right after the upload -----------------
# Shows the (decimated) original meshes side by side, with the rotations
Expand All @@ -1017,6 +1017,6 @@ def _prepare_one(i: int):
mesh, color=_fig_colors[i % len(_fig_colors)], opacity=0.9,
name=_labels[uf.file_id], showlegend=True,
))
prev_fig.update_layout(**_scene_layout(650))
prev_fig.update_layout(**app_helpers.scene_layout(650))
plot_box.plotly_chart(prev_fig, width="stretch")
st.caption(t("app.preview.caption"))
7 changes: 5 additions & 2 deletions app_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,14 @@ def load_preview_mesh(data: bytes, scale: float, name: str) -> trimesh.Trimesh:
mesh = inlayer.load_mesh(io.BytesIO(data), name, file_type="stl")
if scale != 1.0:
mesh.apply_scale(scale)
return decimate_mesh(mesh, PREVIEW_FACE_BUDGET)
mesh = decimate_mesh(mesh, PREVIEW_FACE_BUDGET)
if not (mesh.area > 0):
raise ValueError(t("error.not_solid", name=name))
return mesh


def scene_layout(height: int) -> dict:
"""Gemeinsames Plotly-Layout fuer Vorschau und Ergebnis-Ansicht."""
"""Shared Plotly layout for preview and result views."""
return dict(
template="plotly_dark",
scene=dict(
Expand Down
4 changes: 0 additions & 4 deletions i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -580,10 +580,6 @@ def t(key: str, /, **kwargs: object) -> str:
"de": "Generierter Einleger (Inlay)",
"en": "Generated insert (inlay)",
},
"app.trace.figure": {
"de": "Figur {i}",
"en": "Figure {i}",
},
"app.trace.figure_named": {
"de": "Figur {i} ({name})",
"en": "Figure {i} ({name})",
Expand Down
24 changes: 17 additions & 7 deletions inlayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ def prepare_figure(
# no topology. Watertightness is what matters: it decides whether vox.fill()
# hits the interior instead of running outwards.
t = _log(t_("pipeline.repair"))
if m.is_watertight and m.is_winding_consistent:
if m.is_volume:
_log(t_("pipeline.repair_skipped", faces=i18n.format_int(len(m.faces))), t)
else:
mf = pymeshfix.MeshFix(m.vertices, m.faces)
Expand Down Expand Up @@ -813,7 +813,7 @@ def _recess_pair(

def _wall_check(
box: Manifold, cutters: list[Manifold], inlay: Manifold, config: Config,
apothem: float | None = None,
apothem: float | None = None, solids: list[Manifold] | None = None,
) -> dict:
"""Measures every wall of the finished inlay exactly, per figure.

Expand All @@ -834,13 +834,15 @@ def _wall_check(

def flag(kind: str, figure: int | None, measured: float, target: float,
other: int | None = None) -> None:
outer.append(float(measured))
violations.append({"figure": figure, "kind": kind, "measured_mm": round(float(measured), 3),
"target_mm": float(target), "other": other})

clips = [cutter ^ box for cutter in cutters]
bounds: list[np.ndarray | None] = []
for i, clip in enumerate(clips):
if clip.is_empty() or clip.volume() < _MIN_VOLUME_MM3:
body = (solids[i] ^ box) if solids is not None else clip
if body.is_empty() or body.volume() < _MIN_VOLUME_MM3:
flag("no_cavity", i, 0.0, wall)
bounds.append(None)
continue
Expand Down Expand Up @@ -931,6 +933,8 @@ def build_inlay(
"""
if isinstance(figures, trimesh.Trimesh):
figures = [figures]
if not figures:
raise ValueError(t_("error.no_meshes"))
# Validate up front: a value outside [-1, 1] would push a recess past the
# figure's footprint, and failing after the CSG run would waste the build.
for value in individual_recess_positions or []:
Expand Down Expand Up @@ -1061,8 +1065,10 @@ def solidify_logged(i: int) -> trimesh.Trimesh:
t = _log(t_("pipeline.csg", label=csg_label))
try:
box_m = _to_manifold(box)
solids_m = [_to_manifold(s) for s in solids]
cutters = [
Manifold.batch_boolean([_to_manifold(m) for m in [solids[i]] + recesses[i]], OpType.Add)
Manifold.batch_boolean([solids_m[i]] + [_to_manifold(r) for r in recesses[i]], OpType.Add)
if recesses[i] else solids_m[i]
for i in range(n)
]
inlay_m = box_m - Manifold.batch_boolean(cutters, OpType.Add)
Expand All @@ -1073,7 +1079,7 @@ def solidify_logged(i: int) -> trimesh.Trimesh:
raise ValueError(t_("error.csg_empty"))
_log(t_("pipeline.csg_result", faces=i18n.format_int(len(inlay.faces))), t)

wall_check = _wall_check(box_m, cutters, inlay_m, config, apothem)
wall_check = _wall_check(box_m, cutters, inlay_m, config, apothem, solids_m)

# Box corner to the origin
shift = np.array([centre[0] - box_w / 2.0, centre[1] - box_d / 2.0, -box_h])
Expand Down Expand Up @@ -1289,8 +1295,12 @@ def main(argv: list[str] | None = None) -> int:
# 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 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
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
Expand Down
5 changes: 3 additions & 2 deletions tests/test_app_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,10 @@ def test_large_mesh_is_decimated(self):
[b"", bytes(84), b"solid x\nendsolid x\n", bytes(range(256)) * 2,
binary_stl(np.full((12, 3, 3), np.nan)),
binary_stl(np.concatenate([trimesh.creation.box().triangles,
[[[0, 0, 0], [1, 0, 0], [np.nan, 1, 0]]]]))],
[[[0, 0, 0], [1, 0, 0], [np.nan, 1, 0]]]])),
binary_stl(np.ones((app_helpers.PREVIEW_FACE_BUDGET + 10, 3, 3)))],
ids=["zero-bytes", "binary-header-only", "ascii-no-facets", "garbage", "all-nan",
"one-nan-triangle"],
"one-nan-triangle", "decimates-to-empty"],
)
def test_empty_or_garbled_upload_names_the_file(self, data):
"""An empty mesh used to crash the preview on `mesh.bounds[0][0]`."""
Expand Down
20 changes: 16 additions & 4 deletions tests/test_app_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ def bug(*args, **kwargs):
assert [e.value for e in at.error] == [i18n.TRANSLATIONS["app.error.unexpected"]["en"]]
assert "detail from /srv/inlayer/app.py" in caplog.text

def test_failed_run_clears_previous_result(self):
"""A failed run must not leave the previous run's dashboard on screen."""
at = _upload(_run("en"), [("good.stl", _stl([10, 10, 10]))])
_widget(at, "slider", "voxel_pitch").set_value(1.0).run()
at.button[0].click().run()
assert "result" in at.session_state
_upload(at, [("sheet.stl", self.SHEET)])
at.button[0].click().run()
assert "result" not in at.session_state


class TestUploadLimit:
"""One run takes at most app_helpers.MAX_UPLOAD_FILES uploads."""
Expand All @@ -131,12 +141,13 @@ def pipeline(*args, **kwargs):

monkeypatch.setattr(inlayer, "build_inlay", pipeline)
n = app_helpers.MAX_UPLOAD_FILES + 1
expected = [i18n.t("app.error.too_many_files", n=n, limit=app_helpers.MAX_UPLOAD_FILES)]
at = _upload(_run("en"), self._files(n))
assert [e.value for e in at.error] == expected
assert not at.get("plotly_chart")
at.button[0].click().run()
assert not at.exception
assert [e.value for e in at.error] == [
i18n.t("app.error.too_many_files", n=n, limit=app_helpers.MAX_UPLOAD_FILES)
]
assert [e.value for e in at.error] == expected
assert "result" not in at.session_state

def test_the_limit_itself_reaches_the_pipeline(self, monkeypatch):
Expand Down Expand Up @@ -562,6 +573,7 @@ def test_session_keeps_only_slim_geometry(self):
"""Review N20: the full inlay (with its cavity grid) and the dilated
figures sat in every session's state."""
res = self._generate(_two_figures()).session_state["result"]
assert not {"inlay", "fig_offsets", "xy_translations", "z_offsets"} & set(res)
assert not {"inlay", "fig_meshes", "fig_cache_keys", "fig_offsets", "xy_translations", "z_offsets"} & set(res)
assert res["inlay_viz"].metadata == {}
assert all(m.metadata == {} for m in res["fig_viz"])
assert len(res["placements"]) == 2
4 changes: 4 additions & 0 deletions tests/test_build_inlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ def test_removed_keyword_is_rejected(self, keyword):
class TestBuildInlayMultiMesh:
"""Tests fuer Multi-Mesh-Eingabe (Liste von Figuren)."""

def test_empty_figures_list_raises(self, fast_test_config):
with pytest.raises(ValueError, match="At least one mesh"):
inlayer.build_inlay([], fast_test_config)

def test_multi_mesh_returns_valid_inlay(self, dilated_cube, dilated_sphere, fast_test_config):
"""Two meshes (unarranged - build_inlay lays them out) give two pockets."""
inlay, w, d, h = inlayer.build_inlay([dilated_cube, dilated_sphere], fast_test_config)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_geometry_invariants.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,22 @@ def test_check_matches_the_measured_side_wall(self, offset_x):
check = inlay.metadata["wall_check"]
assert check["min_wall_mm"] == pytest.approx(measured, abs=0.01)
assert check["passes_min_wall"] is (measured >= cfg.wall_thickness - TOL)


class TestFinishedCavityClearance:
"""Measures the finished cavity in the inlay against the input figure."""

def test_flat_wall_clearance_stays_within_documented_voxel_band_and_grows(self, cube_stl_path):
gaps = []
for clearance in (0.4, 1.4):
cfg = _cfg(voxel_pitch=0.5, clearance=clearance)
fig = inlayer.prepare_figure(cube_stl_path, cfg)
inlay, w, d, h, _ = _build([fig], cfg)
(pocket,) = gp.cavities(inlay, w, d, h)
lo = pocket.bounding_box()[:3]
hi = pocket.bounding_box()[3:]
# Per-side XY gap between the 10 mm cube and the finished cavity
gaps.append(float(((hi[0] - lo[0]) - 10.0) / 2.0))
# At clearance 0.4 and pitch 0.5, README documents 1-2 x pitch per side
assert 0.5 - TOL <= gaps[0] <= 1.25 + TOL
assert gaps[1] == pytest.approx(gaps[0] + 1.0, abs=0.35)
5 changes: 3 additions & 2 deletions tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,14 +582,15 @@ def test_every_input_is_checked_before_the_first_is_prepared(self, cube_stl_path
assert "[1/4]" not in out

@pytest.mark.parametrize("target", [
"no_such_dir/inlay.stl", ".",
"no_such_dir/inlay.stl", "no_such_dir/", "", ".",
# root may write to a read-only file - the test stage of the Dockerfile runs as root
pytest.param("read_only.stl", marks=pytest.mark.skipif(
getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores file permissions")),
])
def test_output_path_is_checked_before_the_work(self, cube_stl_path, tmp_path, capsys, target):
(tmp_path / "read_only.stl").touch(mode=0o444)
code, out, err = run_main(capsys, "-i", cube_stl_path, "-o", tmp_path / target, *FAST)
out = "" if target == "" else f"{tmp_path}/{target}"
code, out, err = run_main(capsys, "-i", cube_stl_path, "-o", out, *FAST)
assert code == 2
assert "Cannot write the output file" in err
assert "[1/4]" not in out
Expand Down
4 changes: 3 additions & 1 deletion tests/test_prepare_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,11 @@ def test_one_non_finite_triangle_is_refused(self, tmp_path, value):
@pytest.mark.parametrize(
"triangles",
[[[[0, 0, 0], [10, 0, 0], [10, 10, 0]], [[0, 0, 0], [10, 10, 0], [0, 10, 0]]],
[[[0, 0, 0], [10, 0, 0], [10, 10, 0]], [[0, 0, 0], [10, 10, 0], [0, 10, 0]],
[[0, 0, 0], [10, 10, 0], [10, 0, 0]], [[0, 0, 0], [0, 10, 0], [10, 10, 0]]],
np.ones((12, 3, 3)),
[[[k, 0, 0], [k + 1, 0, 0], [k + 2, 0, 0]] for k in range(12)]],
ids=["flat-square", "collapsed-to-a-point", "collinear"],
ids=["flat-square", "double-sided-sheet", "collapsed-to-a-point", "collinear"],
)
def test_file_without_volume_names_the_file(self, tmp_path, fast_test_config, triangles):
"""Triangles, but nothing the repair could close into a solid: it
Expand Down
Loading
Loading