Files
POPS/app/stl_analysis.py
Martin Hohenberg 6a1f146d8e Background STL analysis with computing spinner; manual geometry override
- analyse_in_background() runs in FastAPI BackgroundTasks with its own
  DB session; _in_progress set prevents duplicate concurrent analyses
- Job detail shows a spinner + auto-reloads every 3s while computing
- 'Compute now' button also triggers background analysis
- StlCache.manually_set flag (migration 0011): entries marked manual are
  never overwritten by auto-analysis
- 'Override values' collapsible form on job detail lets user set
  bounding box and volume directly from slicer data

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 11:07:44 +02:00

73 lines
2.2 KiB
Python

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"}
_in_progress: set[str] = set()
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
loaded = trimesh.load(str(filepath))
if isinstance(loaded, trimesh.Scene):
mesh = trimesh.util.concatenate(list(loaded.geometry.values()))
else:
mesh = loaded
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 analyse_in_background(filename: str) -> None:
"""Run analyse() in a background task with its own DB session."""
if filename in _in_progress:
return
_in_progress.add(filename)
try:
from app.db import SessionLocal
db = SessionLocal()
try:
analyse(filename, db)
finally:
db.close()
finally:
_in_progress.discard(filename)
def is_computing(filename: str) -> bool:
return filename in _in_progress
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}