8000 Fix sizing errors in scans and STL exports by jasonmadigan · Pull Request #234 · tracefinity/tracefinity · GitHub
[go: up one dir, main page]

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
3 changes: 3 additions & 0 deletions .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ jobs:
E2E_TEST_MODE: '1'
GOOGLE_API_KEY: 'mock'

- name: Check physical dimensions through browser and STL export
run: make test-e2e-accuracy

- name: Upload report
if: failure()
uses: actions/upload-artifact@v4
Expand Down
3 changes: 3 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ For feature requests, substantial product changes, or issue/PR scope decisions,
also read [CONSTITUTION.md](CONSTITUTION.md) and use the `scope-triage` skill.
Read [DESIGN.md](DESIGN.md) before making architectural changes.

Before writing public issues, PRs, comments, commit messages or release notes,
follow [the public writing rules](CONTRIBUTING.md#public-writing).

Tracefinity turns photos or scans of physical objects into fitted,
Gridfinity-compatible storage. The backend is Python/FastAPI with OpenCV and
manifold3d; the frontend is Next.js/React/TypeScript with react-three-fiber.
Expand Down
8 changes: 1 addition & 7 deletions CONSTITUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ guide.

### Free, open source, and self-hostable

Tracefinity will remain free, open source, and self-hostable. The hosted service
exists for people who would rather not run it themselves and helps fund the
project. It will not reserve product features for subscribers.
Tracefinity will remain free, open source, and self-hostable.

Installing Tracefinity may involve downloading container images, model weights,
or dependencies. Once it is installed and its local models are available, the
Expand Down Expand Up @@ -139,10 +137,6 @@ deployment, and maintainability do not need to move a photo through the pipeline
to belong here. They qualify when they protect or enable the core product without
introducing a second product mode.

Service-only billing, quotas, monitoring, backups, and abuse controls can exist
around the hosted deployment. They are operating concerns, not a proprietary
feature tier in the core application.

## How we decide

Scope and priority are separate gates.
Expand Down
22 changes: 22 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ GitHub Actions has no event for new reactions. Scheduled reaction polling and
stored baselines are deferred until repository activity justifies that added
machinery.

## Public writing

Keep all repository content strictly about the core software. Issues, pull
requests, comments, commit messages and release notes must describe the technical
problem, reproduction, change and verification directly. Do not include reporter
details or context from outside the core project.

## Pull requests

Keep a pull request focused on one concern. Split unrelated UI polish, developer
Expand Down Expand Up @@ -85,3 +92,18 @@ If your local environment differs, run the equivalent complete backend and
frontend suites and say exactly what you ran in the pull request. Compilation or
`py_compile` alone is not test evidence. Tests should assert the behaviour being
changed, not just that some output was produced.

For changes to calibration, tracing coordinates or export dimensions, also run
`make test-e2e-accuracy`. Install Chromium first with
`cd frontend && pnpm exec playwright install chromium`.

These tests upload a photo of a known flat 80 × 30 mm rectangle and measure the
STL downloaded through the browser. Accurate output must stay within 1 mm of
the expected dimensions and boundary, including clearance. Smooth output must
stay within 1 mm on dimensions and fit the whole physical tool.

The suite starts isolated servers on ports 8011 and 4011 with temporary storage.
Segmentation uses the submitted pixels in place of a hosted model, and U2-Net
is disabled. Calibration, tracing and STL generation run normally. This checks
software accuracy; it does not measure model quality or perspective enlargement
of objects raised above the paper. CI runs it alongside the workflow tests.
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: dev test-e2e test-e2e-ui lint lint-backend lint-frontend lint-fix
.PHONY: dev test-e2e test-e2e-ui test-e2e-accuracy lint lint-backend lint-frontend lint-fix

dev:
@trap 'kill 0' EXIT; \
Expand All @@ -12,6 +12,9 @@ test-e2e:
test-e2e-ui:
cd frontend && E2E_TEST_MODE=1 GOOGLE_API_KEY=mock pnpm exec playwright test --ui

test-e2e-accuracy:
cd frontend && pnpm exec playwright test --config=playwright.accuracy.config.ts

lint: lint-backend lint-frontend

lint-backend:
Expand Down
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@

## Quick Start

Try it at [tracefinity.net](https://tracefinity.net) without installing anything, or self-host:

### Docker

```bash
Expand Down
21 changes: 17 additions & 4 deletions backend/app/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
from app.services.ai_tracer import AITracer
from app.services.bin_service import sync_placed_tools
from app.services.bin_store import BinStore
from app.services.generation_lock import generation_lock
from app.services.geometry import optimal_rotation_angle as _optimal_rotation_angle
from app.services.image_ingest import ImageTooLargeError, ingest_image
from app.services.image_processor import ImageProcessor
Expand All @@ -107,7 +108,7 @@
)
from app.services.project_store import ProjectStore
from app.services.session_store import SessionStore
from app.services.stl_generator_manifold import STL_GEOMETRY_VERSION, ManifoldSTLGenerator
from app.services.stl_generator_manifold import STL_GEOMETRY_VERSION, ManifoldSTLGenerator, bin_interior_inset
from app.services.store_errors import StoreClosedError
from app.services.tool_namer import name_polygons
from app.services.tool_store import ToolStore
Expand Down Expand Up @@ -573,9 +574,9 @@ def _build_bin_from_tools(
tool_height = max(all_ys) - min(all_ys)

clearance = bc.cutout_clearance
wall = bc.wall_thickness
needed_w = tool_width + 2 * clearance + 2 * wall + 0.5
needed_h = tool_height + 2 * clearance + 2 * wall + 0.5
inset = bin_interior_inset(bc.wall_thickness, bc.stacking_lip)
needed_w = tool_width + 2 * clearance + 2 * inset + 0.5
needed_h = tool_height + 2 * clearance + 2 * inset + 0.5

# snap to 0.5 units when half-grid is on, whole units otherwise
if bc.half_grid_base:
Expand Down Expand Up @@ -1299,6 +1300,12 @@ async def update_polygons(request: Request, session_id: str, req: PolygonsReques
def generate_stl(request: Request, session_id: str, req: GenerateRequest, user_id: str = Depends(get_user_id)):
user_sessions, _, _ = get_stores(user_id)
up = _user_path(user_id)
with generation_lock(up, session_id):
user_sessions.ensure_open()
return _generate_session_stl(session_id, req, user_id, user_sessions, up)


def _generate_session_stl(session_id: str, req: GenerateRequest, user_id: str, user_sessions: SessionStore, up: Path):
session = user_sessions.get(session_id)
if not session or not session.scale_factor:
raise HTTPException(status_code=400, detail="must trace tools first")
Expand Down Expand Up @@ -2184,6 +2191,12 @@ async def delete_bin(request: Request, bin_id: str, user_id: str = Depends(get_u
def generate_bin_stl(request: Request, bin_id: str, user_id: str = Depends(get_user_id)):
_, user_tools, user_bins = get_stores(user_id)
up = _user_path(user_id)
with generation_lock(up, bin_id):
user_bins.ensure_open()
return _generate_bin_stl(bin_id, user_id, user_tools, user_bins, up)


def _generate_bin_stl(bin_id: str, user_id: str, user_tools: ToolStore, user_bins: BinStore, up: Path):
bin_data = user_bins.get(bin_id)
if not bin_data:
raise HTTPException(status_code=404, detail="bin not found")
Expand Down
21 changes: 21 additions & 0 deletions backend/app/services/generation_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import threading
from pathlib import Path
from weakref import WeakValueDictionary

_locks: WeakValueDictionary = WeakValueDictionary()
_guard = threading.Lock()


def generation_lock(user_path: Path, entity_id: str):
"""Serialize writers of one export within the storage-owning process.

Hold the lock before reading saved geometry, through publishing outputs.
Waiters keep a strong reference; idle locks disappear from the registry.
"""
key = (user_path.resolve(), entity_id)
with _guard:
lock = _locks.get(key)
if lock is None:
lock = threading.Lock()
_locks[key] = lock
return lock
23 changes: 20 additions & 3 deletions backend/app/services/image_processor.py
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,22 @@ def _detect_paper(self, img: np.ndarray) -> list[tuple[float, float]] | None:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Closed sheet edges preserve perspective and survive illumination
# gradients that truncate or merge a brightness-thresholded region.
edge_candidates = [self._detect_canny(gray, 50, 150), self._detect_canny(gray, 75, 200)]
for edges in edge_candidates:
result = self._find_paper_contour(edges, min_area, max_area, edge_margin, h, w)
if result and self._has_paper_fill(gray, result):
return result

bright_result = self._detect_bright_region(img, gray, min_area, max_area, edge_margin, h, w)
if bright_result:
return bright_result

strategies = [
self._detect_canny(gray, 50, 150),
edge_candidates[0],
self._detect_canny(gray, 30, 100),
self._detect_canny(gray, 75, 200),
edge_candidates[1],
self._detect_adaptive_threshold(gray),
self._detect_saturation(img),
]
Expand All @@ -187,6 +195,16 @@ def _detect_paper(self, img: np.ndarray) -> list[tuple[float, float]] | None:

return None

def _has_paper_fill(self, gray: np.ndarray, corners: list[tuple[float, float]]) -> bool:
"""A strong tool outline must not displace a faint paper boundary."""
region = np.zeros(gray.shape, dtype=np.uint8)
cv2.fillPoly(region, [np.asarray(corners, dtype=np.int32)], 255)
area = cv2.countNonZero(region)
if not area:
return False
bright = cv2.inRange(gray, 180, 255)
return cv2.countNonZero(cv2.bitwise_and(bright, region)) / area >= 0.35

def _detect_bright_region(
self, img: np.ndarray, gray: np.ndarray,
min_area: float, max_area: float, margin: int, h: int, w: int
Expand Down Expand Up @@ -491,4 +509,3 @@ def debug_contour_detection(
results["contour_areas"] = sorted([cv2.contourArea(c) for c in contours], reverse=True)[:10]

return results

8 changes: 6 additions & 2 deletions backend/app/services/stl_generator_manifold.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,11 @@ def _clip_to_interior(
return ext, holes


def bin_interior_inset(wall_thickness: float, stacking_lip: bool) -> float:
"""Wall/lip space reserved by both auto-sizing and pocket clipping."""
return max(wall_thickness, LIP_D0 + LIP_D2 if stacking_lip else 0.0)


def _interior_clip_rect(config):
"""clip boundary for the bin interior in manifold coordinates (centred at origin).

Expand All @@ -795,8 +800,7 @@ def _interior_clip_rect(config):

outer_w = config.grid_x * GF_GRID - 0.5
outer_h = config.grid_y * GF_GRID - 0.5
lip_inset = (LIP_D0 + LIP_D2) if getattr(config, "stacking_lip", False) else 0.0
inset = max(config.wall_thickness, lip_inset)
inset = bin_interior_inset(config.wall_thickness, getattr(config, "stacking_lip", False))
hw = outer_w / 2 - inset
hh = outer_h / 2 - inset
return _SPoly([(-hw, -hh), (hw, -hh), (hw, hh), (-hw, hh)])
Expand Down
44 changes: 44 additions & 0 deletions backend/tests/e2e_accuracy_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Isolated browser-test server; only model inference is substituted.

No fixed polygons or scale factors: the substitute segments the actual image
submitted to the provider. Everything from upload through STL export is real.
"""

import os
import tempfile
from unittest.mock import patch

from fastapi.responses import Response

from tests.physical_size_fixture import rectangle_mask, synthetic_photo

storage = tempfile.TemporaryDirectory(prefix="tracefinity-physical-e2e-")
os.environ.update(
STORAGE_PATH=storage.name,
DEVELOPMENT_MODE="1",
AUTH_MODE="open",
TRACERS="replicate",
REPLICATE_API_TOKEN="synthetic-fixture-only",
TOOL_LABEL_PROVIDER="none",
)
os.environ.pop("E2E_TEST_MODE", None)

from app.services.image_processor import ImageProcessor

with patch.object(ImageProcessor, "__init__", lambda self: setattr(self, "_tool_mask_session", None)):
from app.main import app

import app.services.remote_saliency as remote


async def infer_rectangle(client, config, data_uri):
return rectangle_mask(data_uri)[0]


remote._via_replicate = infer_rectangle


@app.get("/__accuracy/photo.jpg")
def photo():
content, _, _ = synthetic_photo((210, 297))
return Response(content, media_type="image/jpeg")
16 changes: 16 additions & 0 deletions backend/tests/fixtures/paper-corners/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
These photos were taken by Jason Madigan and explicitly provided for use as
Tracefinity test fixtures. The fixtures were
resized through image ingest to 1536 × 2048 pixels; re-encoding removed EXIF,
including location metadata.

| Fixture | Original | Regression |
| --- | --- | --- |
| `bevel-square.jpg` | `IMG_2777.jpeg` | Uneven lighting cuts into the apparent top of the bright paper region. |
| `rafter-square.jpg` | `IMG_2786.jpeg` | Bright tabletop joins the paper region and moves the proposed bottom edge beyond the sheet. |
| `shadowed-pliers.jpg` | `IMG_2904.jpeg` | A brightness contour clips a shaded paper corner. |
| `line-level.jpg` | `IMG_2780.jpeg` | A brightness contour places the top edge inside the shaded sheet, stretching the traced level. |

`test_paper_corners_photos.py` compares detected corners with manually annotated
visible sheet corners. These are calibration regressions, not claims about the
physical dimensions of raised tools. Synthetic photo-to-STL tests separately
check known flat-object dimensions and output clearance.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions backend/tests/measure_pocket.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Measure the browser's downloaded fixture STL, independent of saved tool data."""

import json
import sys

import cv2
import numpy as np
import trimesh
from shapely.geometry import Polygon, box


def measure(path, clearance=1.0):
mesh = trimesh.load(path, force="mesh")
assert mesh.is_watertight, "downloaded bin must be watertight"
# The browser creates a default 4u bin. This plane is below its lip and
# above both the pocket floor and the base's magnet recesses.
section = mesh.section(plane_origin=[0, 0, 25], plane_normal=[0, 0, 1])
assert section is not None, "expected a cavity through z=25 mm"
loops = sorted([Polygon(loop[:, :2]) for loop in section.discrete], key=lambda p: p.area)
assert len(loops) == 2, "expected one exterior and one enclosed tool pocket"
pocket = loops[0]
dimensions = sorted(cv2.minAreaRect(np.array(pocket.exterior.coords, np.float32))[1])
x0, y0, x1, y1 = pocket.bounds
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
# Known 80 x 30 mm source, plus the requested clearance.
half_length, half_width = 40, 15
reference = box(cx - half_length - clearance, cy - half_width - clearance,
cx + half_length + clearance, cy + half_width + clearance)
physical_tool = box(cx - half_length, cy - half_width, cx + half_length, cy + half_width)
return {
"dimensions_mm": dimensions,
"boundary_error_mm": pocket.hausdorff_distance(reference),
"contains_physical_tool": pocket.covers(physical_tool),
"minimum_clearance_mm": pocket.boundary.distance(physical_tool),
}


if __name__ == "__main__":
print(json.dumps(measure(sys.argv[1], *(float(arg) for arg in sys.argv[2:]))))
44 changes: 44 additions & 0 deletions backend/tests/physical_size_fixture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Synthetic flat object and pixel-based inference shared by API/browser tests."""

import base64
import io

import cv2
import numpy as np
from PIL import Image


def synthetic_photo(paper_mm, landscape=False, exif_rotated=False):
width_mm, height_mm = paper_mm
if landscape:
width_mm, height_mm = height_mm, width_mm
px_per_mm = 8
paper = np.full((round(height_mm * px_per_mm), round(width_mm * px_per_mm), 3), 255, np.uint8)
left = (width_mm - 80) / 2 * px_per_mm
top = (height_mm - 30) / 2 * px_per_mm
cv2.rectangle(paper, (round(left), round(top)), (round(left + 80 * px_per_mm), round(top + 30 * px_per_mm)), (0, 0, 0), -1)
photo_size = (3600, 2800) if landscape else (2800, 3600)
w, h = photo_size
corners = np.float32([(w * .12, h * .15), (w * .85, h * .08), (w * .91, h * .86), (w * .08, h * .91)])
source = np.float32([(0, 0), (paper.shape[1], 0), (paper.shape[1], paper.shape[0]), (0, paper.shape[0])])
transform = cv2.getPerspectiveTransform(source, corners)
photo = Image.fromarray(cv2.warpPerspective(paper, transform, photo_size, borderValue=(100, 70, 40)))
exif = Image.Exif()
if exif_rotated:
photo = photo.transpose(Image.Transpose.ROTATE_90)
exif[274] = 6
encoded = io.BytesIO()
photo.save(encoded, format="JPEG", quality=98, exif=exif)
return encoded.getvalue(), corners, photo_size


def rectangle_mask(data_uri):
pixels = Image.open(io.BytesIO(base64.b64decode(data_uri.split(",", 1)[1])))
gray = np.array(pixels.convert("L"))
neutral = np.ptp(np.array(pixels.convert("RGB")), axis=2) < 20
mask = Image.fromarray(np.uint8((gray < 127) & neutral) * 255)
# Exercise provider output resizing, independently of image ingest resizing.
mask = mask.resize((1024, 768), Image.Resampling.NEAREST)
result = io.BytesIO()
mask.save(result, format="PNG")
return result.getvalue(), pixels.size
Loading
Loading
0