1028 lines
43 KiB
Python
1028 lines
43 KiB
Python
# coding=utf-8
|
|
"""Tests de l'extension « Board photo » (pytest).
|
|
|
|
Trois familles : noyau geometrique et traitement d'image (sans inkex), bout
|
|
en bout des trois entrees de menu (inkex requis), traductions et coherence
|
|
des .inx. Le test d'echelle principal genere une photo synthetique en
|
|
perspective et verifie que les trous sont retrouves a 0,5 mm pres.
|
|
"""
|
|
|
|
import base64
|
|
import io
|
|
import math
|
|
import os
|
|
import re
|
|
import socket
|
|
import sys
|
|
import xml.etree.ElementTree as ET
|
|
|
|
import numpy as np
|
|
import pytest
|
|
from PIL import Image
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, os.path.join(HERE, "tests"))
|
|
|
|
import board_photo_core as core # noqa: E402
|
|
import board_photo_remote as remote # noqa: E402
|
|
import board_photo_vision as vision # noqa: E402
|
|
import synthetic as syn # noqa: E402
|
|
|
|
EMPTY_MM = os.path.join(HERE, "tests", "data", "empty_mm.svg")
|
|
EMPTY_PX = os.path.join(HERE, "tests", "data", "empty_px.svg")
|
|
SMALL_MARKERS = os.path.join(HERE, "tests", "data", "small_markers.jpg")
|
|
INX_FILES = ["board_photo_import", "board_photo_markers"]
|
|
TOLERANCE_MM = 0.5
|
|
|
|
|
|
def square(x0, y0, x1, y1, closed=True):
|
|
ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
|
|
return ring + [ring[0]] if closed else ring
|
|
|
|
|
|
def hole_measures(rings):
|
|
"""(centre, diametre equivalent) de chaque trou, tries par abscisse."""
|
|
result = []
|
|
for ring in rings:
|
|
area = abs(core.ring_area(ring))
|
|
result.append((core.ring_centroid(ring), 2 * math.sqrt(area / math.pi)))
|
|
return sorted(result)
|
|
|
|
|
|
def assert_holes_match(rings, scale=1.0, offset=(0.0, 0.0)):
|
|
found = hole_measures([[((x - offset[0]) / scale, (y - offset[1]) / scale)
|
|
for x, y in ring] for ring in rings])
|
|
expected = sorted((center, 2 * radius) for center, radius in syn.HOLES)
|
|
assert len(found) == len(expected)
|
|
for (center, diameter), (true_center, true_diameter) in zip(found, expected):
|
|
assert math.hypot(center[0] - true_center[0],
|
|
center[1] - true_center[1]) < TOLERANCE_MM
|
|
assert abs(diameter - true_diameter) < TOLERANCE_MM
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Noyau : reperes, homographie
|
|
# --------------------------------------------------------------------------
|
|
|
|
def test_parse_color():
|
|
assert core.parse_color("426885887") == ("#1971c2", 1.0)
|
|
assert core.parse_color("#abc") == ("#aabbcc", 1.0)
|
|
assert core.parse_color("pas une couleur") == ("#b3b3b3", 1.0)
|
|
|
|
|
|
def test_polylines_to_d_closed():
|
|
d = core.polylines_to_d([[(0, 0), (1, 2), (3, 0)]], precision=1, closed=True)
|
|
assert d == "M 0.0,0.0 L 1.0,2.0 L 3.0,0.0 Z"
|
|
|
|
|
|
def test_laser_svg_conversion_is_involutive():
|
|
assert core.laser_to_svg((10, 30), 400) == (10.0, 370.0)
|
|
assert core.svg_to_laser(core.laser_to_svg((12.5, 7), 300), 300) == (12.5, 7.0)
|
|
|
|
|
|
def test_marker_layout_origin_bottom_left():
|
|
points = core.marker_layout(400, 15, 20, 370, 350)
|
|
assert points[core.ORIGIN_MARKER] == (15.0, 380.0)
|
|
assert points[core.TOP_LEFT] == (15.0, 30.0)
|
|
assert points[core.TOP_RIGHT] == (385.0, 30.0)
|
|
assert points[core.BOTTOM_RIGHT] == (385.0, 380.0)
|
|
|
|
|
|
def test_layout_problems():
|
|
assert core.layout_problems(400, 400, 15, 15, 370, 370, 20) == []
|
|
assert "outside" in core.layout_problems(400, 400, 15, 15, 380, 370, 20)
|
|
assert "outside" in core.layout_problems(400, 400, 5, 15, 370, 370, 20)
|
|
assert "too_close" in core.layout_problems(400, 400, 15, 15, 30, 370, 20)
|
|
assert core.layout_problems(0, 400, 15, 15, 370, 370, 20) == ["non_positive"]
|
|
# Gabarits de pose : 30 mm d'emprise autour du centre pour des reperes de 20 mm.
|
|
assert core.guide_reach(20) == 30
|
|
assert "outside" in core.layout_problems(400, 400, 15, 15, 370, 370, 20, 30)
|
|
assert core.layout_problems(400, 400, 30, 30, 340, 340, 20, 30) == []
|
|
|
|
|
|
def test_marker_rings():
|
|
ordinary = core.marker_rings((50, 50), 20)
|
|
origin = core.marker_rings((50, 50), 20, origin=True)
|
|
assert len(ordinary) == 2 and len(origin) == 3
|
|
assert abs(abs(core.ring_area(ordinary[0])) - 400) < 1e-9
|
|
assert core.ring_centroid(ordinary[1]) == pytest.approx((50, 50))
|
|
|
|
|
|
def test_homography_maps_points_exactly():
|
|
src = [(120.5, 80.2), (1830.0, 140.7), (1760.3, 1320.9), (90.1, 1250.0)]
|
|
dst = [(15, 15), (385, 15), (385, 385), (15, 385)]
|
|
matrix = core.homography(src, dst)
|
|
assert np.allclose(core.apply_homography(matrix, src), dst, atol=1e-7)
|
|
back = core.homography(dst, src)
|
|
assert np.allclose(core.apply_homography(back @ matrix, src), src, atol=1e-6)
|
|
|
|
|
|
def test_homography_degenerate():
|
|
with pytest.raises(ValueError):
|
|
core.homography([(0, 0), (1, 1), (2, 2), (3, 3)], [(0, 0), (1, 0), (1, 1), (0, 1)])
|
|
|
|
|
|
def test_local_scale():
|
|
matrix = core.homography([(0, 0), (10, 0), (10, 10), (0, 10)],
|
|
[(0, 0), (25, 0), (25, 25), (0, 25)])
|
|
assert core.local_scale(matrix, (5, 5)) == pytest.approx(2.5)
|
|
|
|
|
|
def test_order_corners_and_origin():
|
|
shuffled = [(90, 95), (10, 12), (8, 88), (95, 5)]
|
|
assert core.order_corners(shuffled) == [(10, 12), (95, 5), (90, 95), (8, 88)]
|
|
ordered = ["a", "b", "c", "d"]
|
|
assert core.rotate_to_origin(ordered, 3) == ordered
|
|
assert core.rotate_to_origin(ordered, 1)[core.ORIGIN_MARKER] == "b"
|
|
assert core.rotate_to_origin(ordered, 1) == ["c", "d", "a", "b"]
|
|
|
|
|
|
def test_sheet_layout_fits_a4():
|
|
centers = core.sheet_layout(20)
|
|
side = core.piece_side(20)
|
|
assert len(centers) == 4
|
|
for cx, cy in centers:
|
|
assert side / 2 <= cx <= core.A4[0] - side / 2
|
|
assert side / 2 <= cy <= core.A4[1] - side / 2
|
|
# Meme disposition que sur la surface : origine en bas a gauche.
|
|
tl, tr, br, bl = centers
|
|
assert bl[0] == tl[0] < tr[0] == br[0] and tl[1] == tr[1] < bl[1] == br[1]
|
|
assert tr[0] - tl[0] >= side and bl[1] - tl[1] >= side # pieces disjointes
|
|
assert core.sheet_layout(40) is not None
|
|
assert core.sheet_layout(45) is None
|
|
assert core.sheet_layout(0) is None
|
|
|
|
|
|
def test_piece_ticks_and_guides():
|
|
ticks = core.piece_ticks((50, 50), 20)
|
|
assert len(ticks) == 4
|
|
assert ticks[0] == [(30, 50), (33, 50)] # du bord vers le centre, 3 mm
|
|
guide = core.guide_lines((50, 50), 20)
|
|
assert guide[0][0] == guide[0][-1] == (30, 30) # contour ferme de 40 mm
|
|
xs = [x for line in guide[1:] for x, _y in line]
|
|
assert min(xs) == 20 and max(xs) == 80 # croix : 10 mm de chaque cote
|
|
# Les traits de la piece prolongent exactement la croix du gabarit.
|
|
assert all(y == 50 for line in guide[1:3] + ticks[:2] for _x, y in line)
|
|
|
|
|
|
def test_scale_bar():
|
|
bar = core.scale_bar((10, 100))
|
|
assert bar[0] == [(10, 100), (110, 100)]
|
|
assert len(bar) == 12
|
|
vertical = core.scale_bar((200, 50), vertical=True)
|
|
assert vertical[0] == [(200, 50), (200, 150)]
|
|
assert all(line[1][0] < 200 for line in vertical[1:]) # graduations vers la gauche
|
|
|
|
|
|
def test_print_correction():
|
|
fx, fy = core.print_correction(97, 100)
|
|
assert fx == pytest.approx(100 / 97) and fy == 1.0
|
|
stretched = core.stretch_rings([[(5, 10), (15, 10)]], fx, fy, (105, 148.5))
|
|
# Barre de 10 mm dessinee 10,31 mm : imprimee a 97 %, elle mesure 10 mm.
|
|
length = stretched[0][1][0] - stretched[0][0][0]
|
|
assert length * 0.97 == pytest.approx(10)
|
|
assert stretched[0][0][1] == 10
|
|
|
|
|
|
def test_is_convex_quad():
|
|
assert core.is_convex_quad([(0, 0), (1, 0), (1, 1), (0, 1)])
|
|
assert not core.is_convex_quad([(0, 0), (1, 1), (1, 0), (0, 1)])
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Noyau : contours
|
|
# --------------------------------------------------------------------------
|
|
|
|
def test_mask_to_rings_square():
|
|
mask = np.zeros((6, 6), dtype=bool)
|
|
mask[1:4, 2:5] = True
|
|
rings = core.mask_to_rings(mask)
|
|
assert len(rings) == 1
|
|
# Milieux des aretes : carre 3x3 aux coins coupes de 4 x 1/8.
|
|
assert abs(core.ring_area(rings[0])) == pytest.approx(9 - 0.5)
|
|
assert core.ring_centroid(rings[0]) == pytest.approx((3.5, 2.5))
|
|
|
|
|
|
def test_mask_to_rings_hole_and_diagonal():
|
|
mask = np.ones((7, 7), dtype=bool)
|
|
mask[2:5, 2:5] = False
|
|
assert len(core.mask_to_rings(mask)) == 2
|
|
diagonal = np.array([[1, 0], [0, 1]], dtype=bool)
|
|
rings = core.mask_to_rings(diagonal)
|
|
assert len(rings) == 2 # deux pixels qui ne se touchent que par un coin
|
|
|
|
|
|
def test_simplify_ring_removes_staircase():
|
|
mask = np.zeros((60, 60), dtype=bool)
|
|
rows, cols = np.mgrid[0:60, 0:60]
|
|
mask[(rows - 30) ** 2 + (cols - 30) ** 2 <= 25 ** 2] = True
|
|
ring = core.mask_to_rings(mask)[0]
|
|
simple = core.simplify_ring(ring, 0.6)
|
|
assert len(simple) < len(ring) / 3
|
|
assert abs(core.ring_area(simple)) == pytest.approx(math.pi * 625, rel=0.02)
|
|
assert core.simplify_ring(ring, 0) == ring
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Traitement d'image
|
|
# --------------------------------------------------------------------------
|
|
|
|
def test_label_components_connectivity():
|
|
mask = np.array([[1, 1, 0, 0],
|
|
[0, 0, 1, 0],
|
|
[1, 0, 0, 0],
|
|
[1, 0, 1, 1]], dtype=bool)
|
|
_labels, count4, areas4 = vision.label_components(mask, 4)
|
|
assert count4 == 4 and sorted(areas4[1:].tolist()) == [1, 2, 2, 2]
|
|
labels8, count8, _areas8 = vision.label_components(mask, 8)
|
|
assert count8 == 3
|
|
assert labels8[0, 0] == labels8[1, 2]
|
|
assert vision.label_components(np.zeros((3, 3), bool), 4)[1] == 0
|
|
|
|
|
|
def test_label_components_u_shape():
|
|
# Deux branches reliees seulement par le bas : fusion tardive des plages.
|
|
mask = np.zeros((5, 7), dtype=bool)
|
|
mask[0:4, 1] = mask[0:4, 5] = True
|
|
mask[4, 1:6] = True
|
|
assert vision.label_components(mask, 4)[1] == 1
|
|
|
|
|
|
def test_fill_holes():
|
|
mask = np.ones((9, 9), dtype=bool)
|
|
mask[2:4, 2:4] = False
|
|
mask[5:8, 5:8] = False
|
|
mask[0, 4] = False # encoche au bord : pas un trou
|
|
filled, holes = vision.fill_holes(mask, min_area=5)
|
|
assert len(holes) == 1 and holes[0].sum() == 9
|
|
assert filled[2, 2] and filled[6, 6] and not filled[0, 4]
|
|
|
|
|
|
def test_otsu_threshold():
|
|
values = np.concatenate([np.full(500, 40), np.full(500, 200)]).astype(np.uint8)
|
|
assert 40 <= vision.otsu_threshold(values) < 200
|
|
|
|
|
|
def test_rectify_keeps_pixel_grid():
|
|
"""Homographie identite a 1 px/mm : l'image ressort identique (pas de decalage)."""
|
|
rng = np.random.default_rng(1)
|
|
data = rng.integers(0, 255, (40, 60), dtype=np.uint8)
|
|
image = Image.fromarray(data).convert("RGB")
|
|
result, valid = vision.rectify(image, np.eye(3), 60, 40, 1.0)
|
|
out = np.asarray(result.convert("L"), dtype=int)
|
|
assert result.size == (60, 40) and valid.all()
|
|
assert np.abs(out[2:-2, 2:-2] - data[2:-2, 2:-2].astype(int)).max() <= 2
|
|
|
|
|
|
def test_rectify_scale():
|
|
"""Un point blanc a (30 mm, 10 mm) ressort au bon pixel a 4 px/mm."""
|
|
data = np.zeros((40, 60), dtype=np.uint8)
|
|
data[10, 30] = 255
|
|
image = Image.fromarray(data).convert("RGB")
|
|
result, _valid = vision.rectify(image, np.eye(3), 60, 40, 4.0)
|
|
out = np.asarray(result.convert("L"), dtype=float)
|
|
rows, cols = np.mgrid[0:out.shape[0], 0:out.shape[1]]
|
|
total = out.sum()
|
|
x = ((cols + 0.5) * out).sum() / total / 4.0
|
|
y = ((rows + 0.5) * out).sum() / total / 4.0
|
|
assert (x, y) == pytest.approx((30.5, 10.5), abs=0.05)
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def photo():
|
|
return syn.render_photo()
|
|
|
|
|
|
@pytest.mark.parametrize("rotate", [0, 1, 2, 3])
|
|
def test_detect_markers_any_orientation(rotate):
|
|
picture = syn.render_photo(seed=rotate, rotate=rotate)
|
|
found = vision.detect_markers(vision.gray_array(picture))
|
|
assert found["oriented"]
|
|
assert found["dots"] == [1, 1, 1, 2]
|
|
truth = syn.marker_pixels(rotate)
|
|
for point, true_point in zip(found["points"], truth):
|
|
assert math.hypot(point[0] - true_point[0], point[1] - true_point[1]) < 1.5
|
|
|
|
|
|
def test_printed_markers_on_guides():
|
|
"""Reperes imprimes colles sur leur gabarit : traits et croix ne gene pas."""
|
|
picture = syn.render_photo(seed=7, printed=True)
|
|
found = vision.detect_markers(vision.gray_array(picture))
|
|
assert found["oriented"] and found["dots"] == [1, 1, 1, 2]
|
|
for point, true_point in zip(found["points"], syn.marker_pixels()):
|
|
assert math.hypot(point[0] - true_point[0], point[1] - true_point[1]) < 1.5
|
|
matrix = core.homography(found["points"], syn.markers())
|
|
rectified, valid = vision.rectify(picture, matrix, syn.WIDTH, syn.HEIGHT, 4.0)
|
|
exclude = [(x - 20, y - 20, x + 20, y + 20) for x, y in syn.markers()]
|
|
board = vision.extract_board(vision.gray_array(rectified), valid, 4.0, exclude=exclude)
|
|
assert_holes_match(board["rings"][1:])
|
|
|
|
|
|
def test_detect_markers_small_real_photo():
|
|
"""Vraie photo 800 x 600 : reperes d'environ 22 px, dont deux colles aux
|
|
rails sombres de la machine (le seuil adaptatif large les fragmentait)."""
|
|
found = vision.detect_markers(vision.gray_array(vision.load_photo(SMALL_MARKERS)))
|
|
assert found["oriented"] and found["dots"] == [1, 1, 1, 2]
|
|
truth = [(146, 53), (658, 34), (685, 550), (158, 568)]
|
|
for point, true_point in zip(found["points"], truth):
|
|
assert math.hypot(point[0] - true_point[0], point[1] - true_point[1]) < 3
|
|
|
|
|
|
def test_detect_markers_failure():
|
|
blank = np.full((600, 800), 128, dtype=np.uint8)
|
|
with pytest.raises(vision.MarkerError):
|
|
vision.detect_markers(blank)
|
|
|
|
|
|
def test_dots_near_manual_points(photo):
|
|
dots = vision.dots_near(vision.gray_array(photo), syn.marker_pixels())
|
|
assert dots == [1, 1, 1, 2]
|
|
|
|
|
|
def test_scale_is_respected(photo):
|
|
"""Chaine complete sur photo en perspective : trous retrouves a 0,5 mm pres."""
|
|
found = vision.detect_markers(vision.gray_array(photo))
|
|
matrix = core.homography(found["points"], syn.markers())
|
|
rectified, valid = vision.rectify(photo, matrix, syn.WIDTH, syn.HEIGHT, 4.0)
|
|
assert rectified.size == (1600, 1600)
|
|
exclude = [(x - 20, y - 20, x + 20, y + 20) for x, y in syn.markers()]
|
|
board = vision.extract_board(vision.gray_array(rectified), valid, 4.0, exclude=exclude)
|
|
assert board["holes"] == 3
|
|
assert_holes_match(board["rings"][1:])
|
|
corners = board["rings"][0]
|
|
for true_corner in syn.BOARD:
|
|
assert min(math.hypot(x - true_corner[0], y - true_corner[1])
|
|
for x, y in corners) < 1.0
|
|
expected_area = abs(core.ring_area(syn.BOARD)) - sum(
|
|
math.pi * r * r for _c, r in syn.HOLES)
|
|
assert board["area"] == pytest.approx(expected_area, rel=0.01)
|
|
|
|
|
|
def test_extract_board_none_and_min_hole():
|
|
gray = np.full((200, 200), 60, dtype=np.uint8)
|
|
valid = np.ones_like(gray, dtype=bool)
|
|
assert vision.extract_board(gray, valid, 4.0) is None
|
|
gray[20:180, 20:180] = 210
|
|
gray[50:54, 50:54] = 60 # trou de 1 mm2 : ignore
|
|
gray[100:120, 100:120] = 60 # trou de 25 mm2 : garde
|
|
board = vision.extract_board(gray, valid, 4.0, smoothing=0, min_hole_area=4.0)
|
|
assert board["holes"] == 1
|
|
dark = vision.extract_board(255 - gray, valid, 4.0, lighter=False, smoothing=0)
|
|
assert dark["holes"] == 1
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Bout en bout (necessite inkex)
|
|
# --------------------------------------------------------------------------
|
|
|
|
def run(tmp_path, cls_name, module, source, *args):
|
|
pytest.importorskip("inkex")
|
|
if module == "board_photo_import" and not any(
|
|
str(a).startswith("--marker_placement") for a in args):
|
|
# Scene synthetique : reperes dans la zone de travail (origine 30 mm,
|
|
# ecart 340 mm), donc position personnalisee.
|
|
args = args + ("--marker_placement=custom",)
|
|
extension = getattr(__import__(module), cls_name)
|
|
out = tmp_path / "out.svg"
|
|
extension().run([*args, "--output={}".format(out), str(source)])
|
|
if not out.exists():
|
|
return None # document inchange (message d'erreur)
|
|
import inkex
|
|
return inkex.load_svg(str(out)).getroot()
|
|
|
|
|
|
def layers(svg, key):
|
|
return svg.xpath("//*[@data-board-photo='{}']".format(key))
|
|
|
|
|
|
def outline_rings(svg):
|
|
import inkex
|
|
path = layers(svg, "outline-path")[0]
|
|
return [[(p[1][0], p[1][1]) for p in sub]
|
|
for sub in inkex.Path(path.get("d")).to_superpath()]
|
|
|
|
|
|
def test_markers_end_to_end(tmp_path):
|
|
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM)
|
|
assert svg.get("width") == "400mm" and svg.get("viewBox") == "0 0 400 400"
|
|
paths = layers(svg, "markers")[0].findall("{http://www.w3.org/2000/svg}path")
|
|
assert len(paths) == 4
|
|
origin = paths[core.ORIGIN_MARKER]
|
|
assert origin.get("d").count("M") == 3
|
|
box = origin.bounding_box()
|
|
assert (box.center.x, box.center.y) == pytest.approx((30, 370))
|
|
assert box.width == pytest.approx(20)
|
|
|
|
|
|
def test_markers_print_sheet(tmp_path):
|
|
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
|
|
"--mode=sheet", "--work_width=600")
|
|
assert (svg.get("width"), svg.get("height")) == ("210mm", "297mm")
|
|
sheet = layers(svg, "sheet")[0]
|
|
paths = sheet.findall("{http://www.w3.org/2000/svg}path")
|
|
markers = [p for p in paths if "fill:#000000" in str(p.get("style"))]
|
|
assert len(markers) == 4
|
|
# Taille imprimee exacte : carre de 20 mm, piece de 40 mm.
|
|
assert markers[0].bounding_box().width == pytest.approx(20)
|
|
cuts = [p for p in paths if "stroke-dasharray" in str(p.get("style"))]
|
|
assert len(cuts) == 4 and cuts[0].bounding_box().width == pytest.approx(40)
|
|
bar_x = [p for p in paths if p.label == "Scale bar X"][0]
|
|
bar_y = [p for p in paths if p.label == "Scale bar Y"][0]
|
|
assert bar_x.bounding_box().width == pytest.approx(100)
|
|
assert bar_y.bounding_box().height == pytest.approx(100)
|
|
texts = "".join(t.text or "" for t in sheet.findall("{http://www.w3.org/2000/svg}text"))
|
|
assert "100 %" in texts and "Origin" in texts and "correction" not in texts
|
|
# Tout le dessin tient dans la page A4.
|
|
for path in paths:
|
|
box = path.bounding_box()
|
|
assert 0 < box.left and box.right < 210 and 0 < box.top and box.bottom < 297
|
|
|
|
|
|
def test_markers_print_sheet_correction(tmp_path):
|
|
"""Imprimante qui reduit a 97 % en X : la feuille est dessinee 100/97 plus large."""
|
|
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
|
|
"--mode=sheet", "--print_x=97")
|
|
sheet = layers(svg, "sheet")[0]
|
|
paths = sheet.findall("{http://www.w3.org/2000/svg}path")
|
|
bar_x = [p for p in paths if p.label == "Scale bar X"][0]
|
|
bar_y = [p for p in paths if p.label == "Scale bar Y"][0]
|
|
assert bar_x.bounding_box().width * 0.97 == pytest.approx(100, abs=1e-3)
|
|
assert bar_y.bounding_box().height == pytest.approx(100)
|
|
marker = [p for p in paths if "fill:#000000" in str(p.get("style"))][0]
|
|
box = marker.bounding_box()
|
|
assert box.width * 0.97 == pytest.approx(20, abs=1e-3)
|
|
assert box.height == pytest.approx(20, abs=1e-3)
|
|
texts = "".join(t.text or "" for t in sheet.findall("{http://www.w3.org/2000/svg}text"))
|
|
assert "X 103.1 %, Y 100.0 %" in texts
|
|
for path in paths:
|
|
box = path.bounding_box()
|
|
assert 0 < box.left and box.right < 210 and 0 < box.top and box.bottom < 297
|
|
|
|
|
|
def test_markers_print_sheet_bad_correction(tmp_path, capsys):
|
|
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
|
|
"--mode=sheet", "--print_y=50")
|
|
assert "between 80 and 120 mm" in capsys.readouterr().err
|
|
|
|
|
|
def test_markers_print_sheet_too_large(tmp_path, capsys):
|
|
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
|
|
"--mode=sheet", "--marker_size=60")
|
|
assert "too large for an A4 sheet" in capsys.readouterr().err
|
|
|
|
|
|
def test_markers_guides(tmp_path):
|
|
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
|
|
"--mode=guides")
|
|
assert svg.get("width") == "400mm"
|
|
paths = layers(svg, "guides")[0].findall("{http://www.w3.org/2000/svg}path")
|
|
assert len(paths) == 4 and not layers(svg, "markers")
|
|
box = paths[core.ORIGIN_MARKER].bounding_box()
|
|
assert (box.center.x, box.center.y) == pytest.approx((30, 370))
|
|
assert box.width == pytest.approx(60) # piece de 40 mm + croix de 10 mm
|
|
|
|
|
|
def test_markers_guides_outside(tmp_path, capsys):
|
|
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
|
|
"--mode=guides", "--origin_x=15")
|
|
assert "at least 30 mm from the edges" in capsys.readouterr().err
|
|
|
|
|
|
def test_markers_error(tmp_path, capsys):
|
|
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM, "--spacing_x=390")
|
|
assert "do not fit" in capsys.readouterr().err
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def photo_file(tmp_path_factory, photo):
|
|
path = tmp_path_factory.mktemp("photo") / "board.jpg"
|
|
photo.save(str(path), quality=92)
|
|
return path
|
|
|
|
|
|
def test_import_end_to_end_mm(tmp_path, photo_file, capsys):
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(photo_file))
|
|
assert "3 hole(s)" in capsys.readouterr().err
|
|
assert (svg.get("width"), svg.get("height")) == ("400mm", "400mm")
|
|
image = layers(svg, "photo")[0][0]
|
|
assert [float(image.get(k)) for k in ("x", "y", "width", "height")] == [0, 0, 400, 400]
|
|
assert image.get("preserveAspectRatio") == "none"
|
|
assert layers(svg, "photo")[0].get("sodipodi:insensitive") == "true"
|
|
rings = outline_rings(svg)
|
|
assert len(rings) == 4
|
|
assert_holes_match(rings[1:])
|
|
cuts = layers(svg, "cuts")
|
|
assert len(cuts) == 1
|
|
assert svg.namedview.get("inkscape:current-layer") == cuts[0].get_id()
|
|
# Ordre des calques : photo sous le contour, lui-meme sous Cuts.
|
|
order = [child.get("data-board-photo") for child in svg if child.get("data-board-photo")]
|
|
assert order == ["photo", "outline", "cuts"]
|
|
|
|
|
|
def test_import_keeps_document_scale(tmp_path, photo_file):
|
|
"""Document en px : l'echelle existante est gardee, le resultat reste en mm."""
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_PX,
|
|
"--photo={}".format(photo_file))
|
|
scale = 96 / 25.4
|
|
assert svg.get("width") == "400mm"
|
|
assert svg.unittouu("1mm") == pytest.approx(scale)
|
|
image = layers(svg, "photo")[0][0]
|
|
assert float(image.get("width")) == pytest.approx(400 * scale, rel=1e-6)
|
|
existing = svg.getElementById("existing")
|
|
assert float(existing.get("width")) == 96 # objet existant intact
|
|
assert_holes_match(outline_rings(svg)[1:], scale=scale)
|
|
|
|
|
|
def test_import_twice_replaces_layers(tmp_path, photo_file):
|
|
first = tmp_path / "first"
|
|
first.mkdir()
|
|
run(first, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(photo_file))
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", first / "out.svg",
|
|
"--photo={}".format(photo_file), "--vectorize=false")
|
|
assert len(layers(svg, "photo")) == 1
|
|
assert not layers(svg, "outline") and len(layers(svg, "cuts")) == 1
|
|
|
|
|
|
def test_import_errors(tmp_path, capsys):
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM)
|
|
assert "Choose the photo" in capsys.readouterr().err
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(tmp_path / "nothing.jpg"))
|
|
assert "not found" in capsys.readouterr().err
|
|
|
|
|
|
def test_import_falls_back_to_manual(tmp_path, capsys):
|
|
blank = tmp_path / "blank.jpg"
|
|
Image.new("RGB", (800, 600), (128, 128, 128)).save(str(blank))
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(blank))
|
|
assert "detection failed" in capsys.readouterr().err
|
|
manual = layers(svg, "manual")
|
|
assert len(manual) == 1 and len(manual[0]) == 5
|
|
assert not layers(svg, "photo")
|
|
|
|
|
|
def manual_document(tmp_path, photo, points, scale=0.1):
|
|
"""Photo incorporee (0,1 mm par pixel) + 4 cercles poses sur les reperes."""
|
|
import io
|
|
buffer = io.BytesIO()
|
|
photo.save(buffer, "JPEG", quality=92)
|
|
href = "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode()
|
|
circles = "".join(
|
|
'<circle id="t{}" cx="{}" cy="{}" r="1.5" fill="none" stroke="red"/>'.format(
|
|
k, x * scale + 5, y * scale + 7) for k, (x, y) in enumerate(points))
|
|
source = tmp_path / "manual.svg"
|
|
source.write_text(
|
|
'<svg xmlns="http://www.w3.org/2000/svg" '
|
|
'xmlns:xlink="http://www.w3.org/1999/xlink" '
|
|
'xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" '
|
|
'xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" '
|
|
'width="400mm" height="400mm" viewBox="0 0 400 400">'
|
|
'<sodipodi:namedview id="nv"/>'
|
|
'<g id="manual" inkscape:groupmode="layer" data-board-photo="manual">'
|
|
'<image id="photo" x="0" y="0" width="{}" height="{}" '
|
|
'transform="translate(5,7)" preserveAspectRatio="none" xlink:href="{}"/>'
|
|
'{}</g></svg>'.format(photo.width * scale, photo.height * scale, href, circles),
|
|
encoding="utf-8")
|
|
return source
|
|
|
|
|
|
def test_import_manual_calibration(tmp_path, photo):
|
|
# Cercles donnes dans le desordre : l'ordre et l'orientation sont retrouves.
|
|
points = syn.marker_pixels()
|
|
order = [2, 0, 3, 1]
|
|
source = manual_document(tmp_path, photo, [points[k] for k in order])
|
|
ids = ["--id=photo"] + ["--id=t{}".format(k) for k in range(4)]
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", source, *ids)
|
|
assert not layers(svg, "manual")
|
|
assert_holes_match(outline_rings(svg)[1:])
|
|
|
|
|
|
def test_import_manual_bad_selection(tmp_path, photo, capsys):
|
|
source = manual_document(tmp_path, photo, syn.marker_pixels()[:3])
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", source,
|
|
"--id=photo", "--id=t0", "--id=t1", "--id=t2")
|
|
assert "exactly 4" in capsys.readouterr().err
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Camera distante : faux serveur de capture (memes routes que le serveur Flask)
|
|
# --------------------------------------------------------------------------
|
|
|
|
class Camera:
|
|
"""Faux serveur de capture lance dans son propre processus (tests/fake_camera.py)."""
|
|
|
|
def __init__(self, port, folder):
|
|
self.port = port
|
|
self.folder = folder
|
|
|
|
@property
|
|
def calls(self):
|
|
path = os.path.join(self.folder, "calls.txt")
|
|
if not os.path.exists(path):
|
|
return []
|
|
with open(path) as handle:
|
|
return handle.read().split()
|
|
|
|
def broken(self, value):
|
|
flag = os.path.join(self.folder, "broken")
|
|
if value:
|
|
open(flag, "w").close()
|
|
elif os.path.exists(flag):
|
|
os.remove(flag)
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def camera(tmp_path_factory, photo):
|
|
import subprocess
|
|
folder = tmp_path_factory.mktemp("camera")
|
|
jpeg = folder / "photo.jpg"
|
|
photo.save(str(jpeg), "JPEG", quality=92)
|
|
process = subprocess.Popen(
|
|
[sys.executable, os.path.join(HERE, "tests", "fake_camera.py"), str(jpeg),
|
|
str(folder)], stdout=subprocess.PIPE, text=True)
|
|
try:
|
|
port = int(process.stdout.readline())
|
|
yield Camera(port, str(folder))
|
|
finally:
|
|
process.kill()
|
|
process.wait()
|
|
|
|
|
|
def free_port():
|
|
with socket.socket() as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
return sock.getsockname()[1]
|
|
|
|
|
|
def test_remote_url():
|
|
assert remote.remote_url("192.168.1.20") == "http://192.168.1.20:5000/capture"
|
|
assert remote.remote_url(" 192.168.1.20:8080 ", 5000, "old") == \
|
|
"http://192.168.1.20:8080/old"
|
|
assert remote.remote_url("http://camera.local/photo", 5001) == \
|
|
"http://camera.local:5001/capture"
|
|
assert remote.remote_url("fe80::1", 5000) == "http://[fe80::1]:5000/capture"
|
|
for bad, reason in (("", "no_host"), ("192.168.1.20:99999", "bad_host"),
|
|
("ftp://camera", "bad_host")):
|
|
with pytest.raises(remote.RemoteError) as info:
|
|
remote.remote_url(bad)
|
|
assert info.value.reason == reason
|
|
with pytest.raises(remote.RemoteError):
|
|
remote.remote_url("camera", endpoint="photo")
|
|
|
|
|
|
def test_fetch_photo(camera):
|
|
data = remote.fetch_photo(remote.remote_url("127.0.0.1", camera.port, "old"), 5)
|
|
assert vision.load_photo(data).size == syn.PHOTO_SIZE
|
|
assert camera.calls[-1] == "/old"
|
|
|
|
|
|
def test_fetch_photo_errors(camera):
|
|
camera.broken(True)
|
|
try:
|
|
with pytest.raises(remote.RemoteError) as info:
|
|
remote.fetch_photo(remote.remote_url("127.0.0.1", camera.port), 5)
|
|
assert info.value.reason == "http"
|
|
assert "500" in info.value.detail and "Could not access" in info.value.detail
|
|
finally:
|
|
camera.broken(False)
|
|
before = len(camera.calls)
|
|
with pytest.raises(remote.RemoteError) as info:
|
|
remote.fetch_photo("http://127.0.0.1:{}/cut".format(camera.port), 5)
|
|
assert info.value.reason == "interrupted" and "1000" in info.value.detail
|
|
assert camera.calls[before:] == ["/cut", "/cut"] # une nouvelle tentative
|
|
with pytest.raises(remote.RemoteError) as info:
|
|
remote.fetch_photo("http://127.0.0.1:{}/text".format(camera.port), 5)
|
|
assert info.value.reason == "not_image" and "Photo save" in info.value.detail
|
|
with pytest.raises(remote.RemoteError) as info:
|
|
remote.fetch_photo(remote.remote_url("127.0.0.1", free_port()), 5)
|
|
assert info.value.reason in ("unreachable", "timeout")
|
|
|
|
|
|
def test_import_remote_camera(tmp_path, camera, capsys):
|
|
port = camera.port
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo_source=remote", "--remote_host=127.0.0.1:{}".format(port))
|
|
err = capsys.readouterr().err
|
|
assert "Photo received from http://127.0.0.1:{}/capture".format(port) in err
|
|
assert "3 hole(s)" in err and camera.calls[-1] == "/capture"
|
|
assert_holes_match(outline_rings(svg)[1:])
|
|
|
|
|
|
def test_import_remote_last_photo(tmp_path, camera):
|
|
port = camera.port
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo_source=remote", "--remote_host=127.0.0.1",
|
|
"--remote_port={}".format(port), "--remote_endpoint=old")
|
|
assert camera.calls[-1] == "/old"
|
|
|
|
|
|
def test_rotate_photo():
|
|
from PIL import Image
|
|
image = Image.new("RGB", (4, 2), (0, 0, 0))
|
|
image.putpixel((0, 0), (255, 0, 0)) # coin haut gauche marque
|
|
assert vision.rotate_photo(image, 0) is image
|
|
turned = vision.rotate_photo(image, 90) # sens horaire
|
|
assert turned.size == (2, 4) and turned.getpixel((1, 0)) == (255, 0, 0)
|
|
turned = vision.rotate_photo(image, 180)
|
|
assert turned.size == (4, 2) and turned.getpixel((3, 1)) == (255, 0, 0)
|
|
turned = vision.rotate_photo(image, 270)
|
|
assert turned.size == (2, 4) and turned.getpixel((0, 3)) == (255, 0, 0)
|
|
with pytest.raises(ValueError):
|
|
vision.rotate_photo(image, 45)
|
|
|
|
|
|
@pytest.mark.parametrize("rotation", [90, 180, 270])
|
|
def test_import_remote_rotated(tmp_path, camera, capsys, rotation):
|
|
# La photo tournee reste calibree : les reperes donnent l'orientation.
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo_source=remote", "--remote_host=127.0.0.1",
|
|
"--remote_port={}".format(camera.port), "--remote_endpoint=old",
|
|
"--remote_rotation={}".format(rotation))
|
|
width, height = syn.PHOTO_SIZE
|
|
size = (height, width) if rotation in (90, 270) else (width, height)
|
|
assert "({} x {} px)".format(*size) in capsys.readouterr().err
|
|
assert_holes_match(outline_rings(svg)[1:])
|
|
|
|
|
|
def test_import_remote_errors(tmp_path, camera, capsys):
|
|
port = camera.port
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo_source=remote")
|
|
assert "Enter the address" in capsys.readouterr().err
|
|
camera.broken(True)
|
|
try:
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo_source=remote", "--remote_host=127.0.0.1:{}".format(port))
|
|
finally:
|
|
camera.broken(False)
|
|
assert "returned an error: 500 Error: Could not access the camera" in \
|
|
capsys.readouterr().err
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo_source=remote", "--remote_host=127.0.0.1:{}".format(free_port()),
|
|
"--remote_timeout=3")
|
|
err = capsys.readouterr().err
|
|
assert "cannot be reached" in err or "did not answer in time" in err
|
|
|
|
|
|
CHECK_SVG = """<svg xmlns="http://www.w3.org/2000/svg"
|
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
|
width="200mm" height="200mm" viewBox="0 0 200 200">
|
|
<sodipodi:namedview id="nv"/>
|
|
<g inkscape:groupmode="layer" data-board-photo="outline">
|
|
<path data-board-photo="outline-path" fill-rule="evenodd"
|
|
d="M 0,0 L 100,0 L 100,100 L 0,100 Z M 60,50 A 10,10 0 1 1 40,50 A 10,10 0 1 1 60,50 Z"/>
|
|
</g>
|
|
<g id="cuts" inkscape:groupmode="layer" data-board-photo="cuts">
|
|
<rect id="good" x="5" y="5" width="20" height="20"/>
|
|
<rect id="over_hole" x="45" y="45" width="10" height="10"/>
|
|
<rect id="near_edge" x="1" y="60" width="9" height="10"/>
|
|
<g transform="translate(100,100)"><circle id="outside" cx="50" cy="50" r="5"/></g>
|
|
<circle id="round_good" cx="80" cy="80" r="8"/>
|
|
</g>
|
|
</svg>"""
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Traductions et coherence des .inx
|
|
# --------------------------------------------------------------------------
|
|
|
|
def test_translations_up_to_date_and_complete():
|
|
"""Chaque texte des .inx et des .py a sa traduction dans chaque catalogue."""
|
|
import gettext
|
|
import i18n
|
|
|
|
msgids = [msgid for msgid, _refs in i18n.extract()]
|
|
for name in ("Board photo: import and calibrate",
|
|
"Board photo: print calibration markers"):
|
|
assert name in msgids
|
|
for language in i18n.LANGUAGES:
|
|
entries = i18n.read_po(i18n.po_path(language))
|
|
missing = [m for m in msgids if not entries.get(m, ("", False))[0]]
|
|
assert not missing, "{}.po incomplet : {}".format(language, missing)
|
|
|
|
catalog = gettext.translation(i18n.DOMAIN, i18n.LOCALE_DIR, [language])
|
|
for msgid in msgids:
|
|
assert catalog.gettext(msgid) == entries[msgid][0], \
|
|
"{} : .mo a recompiler (python i18n.py)".format(language)
|
|
|
|
|
|
def test_po_roundtrip(tmp_path):
|
|
import i18n
|
|
|
|
messages = [("Simple", ["a"]), ('Quote "x" and \\ back', ["a"]),
|
|
("Two\nlines", ["a"]), ("Tab\tend\n", ["a"])]
|
|
path = str(tmp_path / "xx.po")
|
|
i18n.write_po(path, "fr", messages,
|
|
{m: ("<" + m + ">", False) for m, _r in messages})
|
|
entries = i18n.read_po(path)
|
|
for msgid, _refs in messages:
|
|
assert entries[msgid] == ("<" + msgid + ">", False)
|
|
|
|
|
|
def inx_params(name):
|
|
"""Valeur par defaut de chaque <param> (premiere option d'un choix sans texte)."""
|
|
root = ET.parse(os.path.join(HERE, name + ".inx")).getroot()
|
|
params = {}
|
|
for elem in root.iter():
|
|
if elem.tag.rsplit("}", 1)[-1] != "param":
|
|
continue
|
|
value = (elem.text or "").strip()
|
|
options = [o for o in elem if o.tag.rsplit("}", 1)[-1] == "option"]
|
|
if not value and options:
|
|
value = options[0].get("value")
|
|
params[elem.get("name")] = value
|
|
return params
|
|
|
|
|
|
@pytest.mark.parametrize("name", INX_FILES)
|
|
def test_inx_matches_arguments(name):
|
|
"""Chaque <param> du .inx a son add_argument avec le meme defaut, et inversement."""
|
|
with open(os.path.join(HERE, name + ".py"), encoding="utf-8") as handle:
|
|
source = handle.read()
|
|
arguments = dict(re.findall(r'add_argument\("--(\w+)"(?:, type=[\w.]+)?, '
|
|
r'default=("?[^")]*"?)\)', source))
|
|
params = inx_params(name)
|
|
assert set(params) == set(arguments)
|
|
for key, value in params.items():
|
|
if key == "tab":
|
|
continue
|
|
default = arguments[key].strip('"')
|
|
if value in ("true", "false"):
|
|
assert default == str(value == "true")
|
|
elif re.match(r"^-?[\d.]+$", value) and re.match(r"^-?[\d.]+$", default):
|
|
assert float(default) == float(value), key
|
|
else:
|
|
assert default == value, key
|
|
|
|
|
|
def test_work_area_settings_identical():
|
|
"""Import et reperes partagent la description de la zone de travail."""
|
|
shared = {k: v for k, v in inx_params("board_photo_markers").items()
|
|
if k not in ("tab", "mode", "print_x", "print_y")}
|
|
imported = inx_params("board_photo_import")
|
|
assert {k: imported[k] for k in shared} == shared
|
|
|
|
|
|
@pytest.mark.parametrize("name", INX_FILES)
|
|
def test_inx_images_exist(name):
|
|
"""Les images de la boite de dialogue sont presentes (chemin relatif au .inx)."""
|
|
root = ET.parse(os.path.join(HERE, name + ".inx")).getroot()
|
|
for elem in root.iter():
|
|
if elem.tag.rsplit("}", 1)[-1] == "image":
|
|
assert os.path.isfile(os.path.join(HERE, elem.text.strip())), elem.text
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Export vers LaserGRBL (extension tierce, simulee : selection et coordonnees)
|
|
# --------------------------------------------------------------------------
|
|
|
|
LASER_COLORS = "#000000,#FF0000,#0000ff" # gravure, decoupe int., decoupe ext.
|
|
|
|
|
|
def lasergrbl_export(svg):
|
|
"""Elements retenus par « Export to LaserGRBL » v1.21 (tout le document) et
|
|
points du G-code de leur trace, en mm depuis le bas gauche de la page."""
|
|
import inkex
|
|
colors = [inkex.Color(c).to_rgba() for c in LASER_COLORS.split(",")]
|
|
to_mm = svg.unit_to_viewport(1, "mm")
|
|
vbox = svg.get_viewbox()
|
|
exported = {}
|
|
for el in svg.descendants():
|
|
ident = el.get("id")
|
|
if el.TAG == "use":
|
|
el = el.unlink()
|
|
if el.TAG in ["rect", "circle", "ellipse"]:
|
|
el = el.to_path_element()
|
|
elif el.TAG != "path":
|
|
continue
|
|
fill = None if "fill" not in el.style or el.style["fill"] == "none" \
|
|
else el.style.get_color("fill")
|
|
col = None if "stroke" not in el.style or el.style["stroke"] == "none" \
|
|
else el.style.get_color("stroke")
|
|
if not any(c in [col, fill] for c in colors):
|
|
continue
|
|
path = el.path.transform(el.composed_transform()).to_superpath()
|
|
exported[ident] = [
|
|
(round((pt[1][0] - vbox[0]) * to_mm, 2),
|
|
round((vbox[1] + vbox[3] - pt[1][1]) * to_mm, 2))
|
|
for sub in path for pt in sub]
|
|
return exported
|
|
|
|
|
|
def with_laser_colors(svg, path):
|
|
"""Enregistre le document avec les couleurs d'export memorisees (<lasergrbl:info>)."""
|
|
path.write_bytes(svg.tostring().replace(
|
|
b"</svg>", '<lasergrbl:info xmlns:lasergrbl="https://lasergrbl.com/inkscape" '
|
|
'colors="{}"/></svg>'.format(LASER_COLORS).encode()))
|
|
return path
|
|
|
|
|
|
def cut_document(tmp_path, photo_file, source):
|
|
"""Import, puis deux formes rouges dans « Cuts » (une sur la planche, une hors
|
|
planche) ; renvoie le document, avec les couleurs d'export memorisees."""
|
|
import inkex
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", source,
|
|
"--photo={}".format(photo_file))
|
|
scale = svg.unittouu("1mm")
|
|
cuts = layers(svg, "cuts")[0]
|
|
# Rectangle de 30 x 20 mm, coin bas gauche en (150, 160) mm repere laser.
|
|
good = inkex.Rectangle.new(150 * scale, (400 - 180) * scale, 30 * scale, 20 * scale)
|
|
good.set("id", "good")
|
|
bad = inkex.Rectangle.new(2 * scale, 2 * scale, 10 * scale, 10 * scale)
|
|
bad.set("id", "bad")
|
|
for shape in (good, bad):
|
|
shape.style = inkex.Style({"fill": "none", "stroke": "#ff0000",
|
|
"stroke-width": str(0.1 * scale)})
|
|
cuts.add(shape)
|
|
placed = with_laser_colors(svg, tmp_path / "cuts.svg")
|
|
return inkex.load_svg(str(placed)).getroot()
|
|
|
|
|
|
@pytest.mark.parametrize("source", [EMPTY_MM, EMPTY_PX])
|
|
def test_lasergrbl_export_origin_and_size(tmp_path, photo_file, source, capsys):
|
|
"""Seules les formes de « Cuts » partent a la laser, a la bonne place et taille,
|
|
en document mm comme px ; photo et contour ne sont pas exportes."""
|
|
pytest.importorskip("inkex")
|
|
svg = cut_document(tmp_path, photo_file, source)
|
|
assert layers(svg, "outline") and layers(svg, "photo")
|
|
exported = lasergrbl_export(svg)
|
|
assert set(exported) == {"good", "bad"}
|
|
xs, ys = zip(*exported["good"])
|
|
assert (min(xs), max(xs), min(ys), max(ys)) == pytest.approx((150, 180, 160, 180),
|
|
abs=0.01)
|
|
|
|
|
|
def test_import_warns_when_page_is_not_the_work_area(tmp_path, photo_file, capsys):
|
|
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(photo_file), "--set_page=false")
|
|
assert "The page is not the size of the work area" in capsys.readouterr().err
|
|
|
|
|
|
def test_corner_layout():
|
|
"""Pieces de 40 mm (reperes de 20) aux angles d'un nid de 400 x 400 mm."""
|
|
assert core.corner_layout(400, 400, 20) == pytest.approx((-20, -20, 440, 440))
|
|
assert core.corner_layout(400, 300, 17.5) == pytest.approx((-17.5, -17.5, 435, 335))
|
|
|
|
|
|
@pytest.mark.parametrize("name", ["board_photo_import", "board_photo_markers"])
|
|
def test_inx_accepts_negative_origin(name):
|
|
"""Le dialogue doit accepter un repere origine hors de la zone (X, Y < 0)."""
|
|
root = ET.parse(os.path.join(HERE, name + ".inx")).getroot()
|
|
for elem in root.iter():
|
|
if elem.get("name") in ("origin_x", "origin_y"):
|
|
assert float(elem.get("min")) < 0
|
|
|
|
|
|
def test_photo_extent():
|
|
"""Reperes dans la zone : la photo couvre la zone seule ; reperes autour :
|
|
elle s'agrandit pour les montrer, bornes sur la grille des pixels."""
|
|
assert core.photo_extent(400, 400, 30, 30, 340, 340, 20, 4.0) == (0, 0, 400, 400)
|
|
x0, y0, x1, y1 = core.photo_extent(400, 400, -21.5, -18, 443, 436, 20, 4.0)
|
|
assert (x0, x1) == pytest.approx((-51.5, 451.5))
|
|
assert (y0, y1) == pytest.approx((-48, 448))
|
|
x0, _y0, _x1, _y1 = core.photo_extent(400, 400, -21.3, -18, 443, 436, 20, 3.0)
|
|
assert x0 * 3.0 == pytest.approx(round(x0 * 3.0)) and x0 <= -51.3
|
|
|
|
|
|
def test_rectify_with_offset():
|
|
"""Une photo couvrant (-50, -50)-(450, 450) mm place chaque point au bon pixel."""
|
|
picture = syn.render_photo()
|
|
matrix = core.homography(syn.marker_pixels(), syn.markers())
|
|
wide, valid = vision.rectify(picture, matrix, 500, 500, 2.0, offset=(-50, -50))
|
|
area, _valid = vision.rectify(picture, matrix, 400, 400, 2.0)
|
|
assert wide.size == (1000, 1000)
|
|
inner = np.asarray(wide.convert("L"), dtype=float)[100:900, 100:900]
|
|
assert np.abs(inner - np.asarray(area.convert("L"), dtype=float)).mean() < 2
|
|
|
|
|
|
def test_import_markers_at_honeycomb_corners(tmp_path, photo_file):
|
|
"""Reperes aux angles du nid d'abeille (reglage par defaut) : origine et ecart
|
|
deduits, la photo deborde de la page pour les montrer.
|
|
|
|
Dans la scene synthetique, les pieces (40 mm) touchent les angles du carre
|
|
(50, 50)-(350, 350) : c'est le nid d'abeille de 300 x 300 mm vu ici."""
|
|
pytest.importorskip("inkex")
|
|
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(photo_file))
|
|
reference = outline_rings(svg)
|
|
out = tmp_path / "corners"
|
|
out.mkdir()
|
|
svg = run(out, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
|
|
"--photo={}".format(photo_file), "--work_width=300", "--work_height=300",
|
|
"--marker_placement=corners")
|
|
image = layers(svg, "photo")[0][0]
|
|
box = [float(image.get(k)) for k in ("x", "y", "width", "height")]
|
|
assert box == pytest.approx([-50, -50, 400, 400])
|
|
assert (svg.get("width"), svg.get("height")) == ("300mm", "300mm")
|
|
shifted = outline_rings(svg)
|
|
assert len(shifted) == len(reference)
|
|
xs = [p[0] for p in shifted[0]]
|
|
ref_xs = [p[0] for p in reference[0]]
|
|
assert min(xs) == pytest.approx(min(ref_xs) - 50, abs=0.5)
|
|
|
|
|