Analyse STL/3MF on upload: bounding box + volume, cached in stl_cache

- StlCache model: filename, cube_x/y/z (mm), volume_ccm
- Migration 0007: stl_cache table
- app/stl_analysis.py: trimesh-based analyse() + get_cache_map()
  - Runs immediately after upload in both /jobs and /brackets/{id}/jobs
  - Skips .gcode (no geometry), caches per filename, idempotent
- Library selector in both modals now shows dimensions and volume
- requirements: trimesh==4.5.3

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Martin Hohenberg
2026-06-18 22:04:11 +02:00
parent ccf6a64787
commit 4c7acb1c52
8 changed files with 116 additions and 5 deletions

47
app/stl_analysis.py Normal file
View File

@@ -0,0 +1,47 @@
import logging
from pathlib import Path
from sqlalchemy.orm import Session
from app.models.stl_cache import StlCache
logger = logging.getLogger("pops")
_ANALYSABLE = {".stl", ".3mf"}
def analyse(filename: str, db: Session) -> StlCache | None:
"""Return cached analysis for filename, computing it if missing."""
existing = db.query(StlCache).filter(StlCache.filename == filename).first()
if existing:
return existing
from app.stl import get_stl_dir
filepath = get_stl_dir() / filename
if Path(filename).suffix.lower() not in _ANALYSABLE or not filepath.exists():
return None
try:
import trimesh
mesh = trimesh.load(str(filepath), force="mesh")
extents = mesh.extents # [size_x, size_y, size_z] in mm
volume_mm3 = abs(mesh.volume) # mm³ (negative for inverted normals)
entry = StlCache(
filename=filename,
cube_x=round(float(extents[0]), 2),
cube_y=round(float(extents[1]), 2),
cube_z=round(float(extents[2]), 2),
volume_ccm=round(volume_mm3 / 1000, 3),
)
db.add(entry)
db.commit()
return entry
except Exception:
logger.exception("STL analysis failed for %s", filename)
return None
def get_cache_map(filenames: list[str], db: Session) -> dict[str, StlCache]:
"""Bulk-fetch cached entries for a list of filenames."""
rows = db.query(StlCache).filter(StlCache.filename.in_(filenames)).all()
return {r.filename: r for r in rows}