feat(print-area): detect die-cut and safe print area
Keep 22827 content on the sticker when Avery bleed guides or printer drift would otherwise print off the label. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ffa4d0cf86
commit
e31c5f89bd
10 files changed
+730
-88
No files matched your search
@@ -24,6 +24,7 @@ a = Analysis(
|
|||||||
"avery_studio.document_import",
|
"avery_studio.document_import",
|
||||||
"avery_studio.import_dialog",
|
"avery_studio.import_dialog",
|
||||||
"avery_studio.template_loader",
|
"avery_studio.template_loader",
|
||||||
|
"avery_studio.print_area",
|
||||||
"avery_studio.avery_download",
|
"avery_studio.avery_download",
|
||||||
"avery_studio.download_dialog",
|
"avery_studio.download_dialog",
|
||||||
"avery_studio.printing",
|
"avery_studio.printing",
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Open-source **Windows desktop** designer for Avery label templates (e.g. **60504
|
|||||||
|
|
||||||
Not affiliated with Avery Products Corporation. MIT licensed.
|
Not affiliated with Avery Products Corporation. MIT licensed.
|
||||||
|
|
||||||
## Features (v0.1)
|
## Features (v0.2)
|
||||||
|
|
||||||
- **No templates shipped** — start on **Select a template**
|
- **No templates shipped** — start on **Select a template**
|
||||||
- Remembers your **last used** template on next launch
|
- Remembers your **last used** template on next launch
|
||||||
@@ -17,6 +17,7 @@ Not affiliated with Avery Products Corporation. MIT licensed.
|
|||||||
- Templates live in `%LOCALAPPDATA%\AveryLabelStudio\templates`
|
- Templates live in `%LOCALAPPDATA%\AveryLabelStudio\templates`
|
||||||
- Import artwork (PDF/Word) with contain / cover / stretch
|
- Import artwork (PDF/Word) with contain / cover / stretch
|
||||||
- Print / Print Preview / multi-sheet projects
|
- Print / Print Preview / multi-sheet projects
|
||||||
|
- Detect die-cut vs bleed vs safe print area (print-to-edge templates like **22827**)
|
||||||
- Build a standalone **`.exe`** with PyInstaller
|
- Build a standalone **`.exe`** with PyInstaller
|
||||||
|
|
||||||
## Templates
|
## Templates
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
"""Avery Label Studio package."""
|
"""Avery Label Studio package."""
|
||||||
|
|
||||||
__version__ = "0.1.0"
|
__version__ = "0.2.0"
|
||||||
@@ -136,6 +136,11 @@ class LabelScene(QGraphicsScene):
|
|||||||
self._bg = self.addRect(0, 0, w, h, QPen(QColor("#94a3b8"), 2), QBrush(QColor(design.background)))
|
self._bg = self.addRect(0, 0, w, h, QPen(QColor("#94a3b8"), 2), QBrush(QColor(design.background)))
|
||||||
self._bg.setZValue(-100)
|
self._bg.setZValue(-100)
|
||||||
self._bg.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
self._bg.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
||||||
|
self._safe = self.addRect(0, 0, w, h)
|
||||||
|
self._safe.setZValue(-90)
|
||||||
|
self._safe.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
||||||
|
self._safe.setAcceptedMouseButtons(Qt.MouseButton.NoButton)
|
||||||
|
self._update_safe_print_area()
|
||||||
self.selectionChanged.connect(self._on_selection)
|
self.selectionChanged.connect(self._on_selection)
|
||||||
self.reload_from_design()
|
self.reload_from_design()
|
||||||
|
|
||||||
@@ -150,6 +155,22 @@ class LabelScene(QGraphicsScene):
|
|||||||
self._items[el.id] = item
|
self._items[el.id] = item
|
||||||
self.design_changed.emit()
|
self.design_changed.emit()
|
||||||
|
|
||||||
|
def _update_safe_print_area(self) -> None:
|
||||||
|
"""Dashed inset: keep text/logos here so printer drift stays on the sticker."""
|
||||||
|
from .template_60504 import TEMPLATE as T
|
||||||
|
|
||||||
|
w = inches_to_scene(T.label_width_in)
|
||||||
|
h = inches_to_scene(T.label_height_in)
|
||||||
|
inset = inches_to_scene(T.recommended_safe_inset_in())
|
||||||
|
if inset <= 0 or inset * 2 >= min(w, h):
|
||||||
|
self._safe.setVisible(False)
|
||||||
|
return
|
||||||
|
self._safe.setVisible(True)
|
||||||
|
self._safe.setRect(inset, inset, w - 2 * inset, h - 2 * inset)
|
||||||
|
self._safe.setPen(QPen(QColor("#ea580c"), 1.4, Qt.PenStyle.DashLine))
|
||||||
|
self._safe.setBrush(QBrush(Qt.BrushStyle.NoBrush))
|
||||||
|
self._safe.setToolTip("Safe print area — keep text inside this dashed rectangle")
|
||||||
|
|
||||||
def resize_to_active_template(self) -> None:
|
def resize_to_active_template(self) -> None:
|
||||||
"""Call after switching Avery template geometry."""
|
"""Call after switching Avery template geometry."""
|
||||||
from .template_60504 import TEMPLATE as T
|
from .template_60504 import TEMPLATE as T
|
||||||
@@ -158,6 +179,7 @@ class LabelScene(QGraphicsScene):
|
|||||||
h = inches_to_scene(T.label_height_in)
|
h = inches_to_scene(T.label_height_in)
|
||||||
self.setSceneRect(0, 0, w, h)
|
self.setSceneRect(0, 0, w, h)
|
||||||
self._bg.setRect(0, 0, w, h)
|
self._bg.setRect(0, 0, w, h)
|
||||||
|
self._update_safe_print_area()
|
||||||
self.reload_from_design()
|
self.reload_from_design()
|
||||||
|
|
||||||
def add_element(self, element: LabelElement) -> ElementItem:
|
def add_element(self, element: LabelElement) -> ElementItem:
|
||||||
|
|||||||
@@ -25,12 +25,19 @@ from .import_settings import ImportSettings
|
|||||||
|
|
||||||
|
|
||||||
class ImportDocumentDialog(QDialog):
|
class ImportDocumentDialog(QDialog):
|
||||||
def __init__(self, settings: ImportSettings | None = None, parent=None) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
settings: ImportSettings | None = None,
|
||||||
|
parent=None,
|
||||||
|
*,
|
||||||
|
recommended_inset_in: float = 0.0,
|
||||||
|
) -> None:
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self.setWindowTitle("Import PDF / Word → Auto-fill 60504 labels")
|
self.setWindowTitle("Import PDF / Word → Auto-fill labels")
|
||||||
self.setMinimumWidth(520)
|
self.setMinimumWidth(520)
|
||||||
self.file_path: Path | None = None
|
self.file_path: Path | None = None
|
||||||
self.settings = settings or ImportSettings()
|
self.settings = settings or ImportSettings()
|
||||||
|
self.recommended_inset_in = max(0.0, recommended_inset_in)
|
||||||
|
|
||||||
root = QVBoxLayout(self)
|
root = QVBoxLayout(self)
|
||||||
|
|
||||||
@@ -95,8 +102,14 @@ class ImportDocumentDialog(QDialog):
|
|||||||
self.spin_inset.setSingleStep(0.01)
|
self.spin_inset.setSingleStep(0.01)
|
||||||
self.spin_inset.setDecimals(3)
|
self.spin_inset.setDecimals(3)
|
||||||
self.spin_inset.setSuffix(" in")
|
self.spin_inset.setSuffix(" in")
|
||||||
self.spin_inset.setValue(self.settings.inset_in)
|
inset_value = self.settings.inset_in
|
||||||
place_l.addRow("Inset", self.spin_inset)
|
if inset_value <= 0 and self.recommended_inset_in > 0:
|
||||||
|
inset_value = self.recommended_inset_in
|
||||||
|
self.spin_inset.setValue(inset_value)
|
||||||
|
inset_label = "Inset"
|
||||||
|
if self.recommended_inset_in > 0:
|
||||||
|
inset_label = f"Inset (safe {self.recommended_inset_in:.3f}\")"
|
||||||
|
place_l.addRow(inset_label, self.spin_inset)
|
||||||
|
|
||||||
self.spin_cx = QDoubleSpinBox()
|
self.spin_cx = QDoubleSpinBox()
|
||||||
self.spin_cy = QDoubleSpinBox()
|
self.spin_cy = QDoubleSpinBox()
|
||||||
@@ -119,11 +132,17 @@ class ImportDocumentDialog(QDialog):
|
|||||||
place_l.addRow("Render DPI", self.spin_dpi)
|
place_l.addRow("Render DPI", self.spin_dpi)
|
||||||
root.addWidget(place)
|
root.addWidget(place)
|
||||||
|
|
||||||
note = QLabel(
|
note_text = (
|
||||||
"Example: a 10-page PDF → 10 labels → 3 Letter sheets (4+4+2).\n"
|
"Example: a 10-page PDF → 10 labels → 3 Letter sheets (4+4+2).\n"
|
||||||
"Export creates one print PDF with every sheet included.\n"
|
"Export creates one print PDF with every sheet included.\n"
|
||||||
"Word needs Microsoft Word installed (or export to PDF first)."
|
"Word needs Microsoft Word installed (or export to PDF first)."
|
||||||
)
|
)
|
||||||
|
if self.recommended_inset_in > 0:
|
||||||
|
note_text += (
|
||||||
|
f"\nThis template is print-to-edge: a {self.recommended_inset_in:.3f}\" "
|
||||||
|
"inset keeps text on the sticker if the printer feeds slightly off."
|
||||||
|
)
|
||||||
|
note = QLabel(note_text)
|
||||||
note.setWordWrap(True)
|
note.setWordWrap(True)
|
||||||
note.setStyleSheet("color: #64748b;")
|
note.setStyleSheet("color: #64748b;")
|
||||||
root.addWidget(note)
|
root.addWidget(note)
|
||||||
|
|||||||
@@ -88,10 +88,12 @@ class MainWindow(QMainWindow):
|
|||||||
def _status_template_text(self) -> str:
|
def _status_template_text(self) -> str:
|
||||||
if not self.template_ready or not TEMPLATE.id:
|
if not self.template_ready or not TEMPLATE.id:
|
||||||
return "No template selected — download from Avery.com or import a Word blank"
|
return "No template selected — download from Avery.com or import a Word blank"
|
||||||
|
safe = TEMPLATE.recommended_safe_inset_in()
|
||||||
|
extra = f" · safe inset {safe:.3f}\"" if safe > 0 else ""
|
||||||
return (
|
return (
|
||||||
f"{TEMPLATE.name}: panel {TEMPLATE.label_width_in:.4f}\" · "
|
f"{TEMPLATE.name}: panel {TEMPLATE.label_width_in:.4f}\" · "
|
||||||
f"top {TEMPLATE.top_margin_in:.3f}\" · v-gap {TEMPLATE.vertical_gap_in:.3f}\" · "
|
f"top {TEMPLATE.top_margin_in:.3f}\" · v-gap {TEMPLATE.vertical_gap_in:.3f}\" · "
|
||||||
f"{TEMPLATE.labels_per_sheet}/sheet"
|
f"{TEMPLATE.labels_per_sheet}/sheet{extra}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def _build_ui(self) -> None:
|
def _build_ui(self) -> None:
|
||||||
@@ -675,7 +677,11 @@ class MainWindow(QMainWindow):
|
|||||||
)
|
)
|
||||||
self.download_avery_template()
|
self.download_avery_template()
|
||||||
return
|
return
|
||||||
dlg = ImportDocumentDialog(self.project.import_settings, self)
|
dlg = ImportDocumentDialog(
|
||||||
|
self.project.import_settings,
|
||||||
|
self,
|
||||||
|
recommended_inset_in=TEMPLATE.recommended_safe_inset_in(),
|
||||||
|
)
|
||||||
if dlg.exec() != dlg.DialogCode.Accepted:
|
if dlg.exec() != dlg.DialogCode.Accepted:
|
||||||
return
|
return
|
||||||
assert dlg.file_path is not None
|
assert dlg.file_path is not None
|
||||||
|
|||||||
@@ -0,0 +1,393 @@
|
|||||||
|
"""Detect die-cut label grids and inner safe print areas from template rectangles.
|
||||||
|
|
||||||
|
Avery print-to-the-edge blanks (e.g. 22827) often include nested guides:
|
||||||
|
bleed (slightly larger than the sticker), die-cut, and a smaller safe print area.
|
||||||
|
Using the bleed box as the label makes ink land off the sticker when the printer
|
||||||
|
feeds a millimetre off — which happens occasionally.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from statistics import median
|
||||||
|
from typing import Sequence
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_PRINT_TO_EDGE_INSET_IN = 0.125
|
||||||
|
_SIZE_BIN_IN = 0.05
|
||||||
|
_POS_BIN_IN = 0.04
|
||||||
|
_BLEED_SNAP_MIN_IN = 0.03
|
||||||
|
_BLEED_SNAP_MAX_IN = 0.30
|
||||||
|
_PAGE_BORDER_FRAC = 0.92
|
||||||
|
_MIN_LABEL_IN = 0.5
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KnownProduct:
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
marketed_size: str
|
||||||
|
marketed_width_in: float
|
||||||
|
marketed_height_in: float
|
||||||
|
print_to_edge: bool = False
|
||||||
|
default_safe_inset_in: float = 0.0
|
||||||
|
source_url: str = ""
|
||||||
|
compatible: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
KNOWN_PRODUCTS: dict[str, KnownProduct] = {
|
||||||
|
"22827": KnownProduct(
|
||||||
|
id="22827",
|
||||||
|
name="Avery 22827",
|
||||||
|
marketed_size='3.5" x 4.75"',
|
||||||
|
marketed_width_in=3.5,
|
||||||
|
marketed_height_in=4.75,
|
||||||
|
print_to_edge=True,
|
||||||
|
default_safe_inset_in=DEFAULT_PRINT_TO_EDGE_INSET_IN,
|
||||||
|
source_url="https://www.avery.com/templates/22827",
|
||||||
|
compatible=("22932",),
|
||||||
|
),
|
||||||
|
"60504": KnownProduct(
|
||||||
|
id="60504",
|
||||||
|
name="Avery 60504",
|
||||||
|
marketed_size='4" x 4"',
|
||||||
|
marketed_width_in=4.0,
|
||||||
|
marketed_height_in=4.0,
|
||||||
|
print_to_edge=False,
|
||||||
|
source_url="https://www.avery.com/templates/60504",
|
||||||
|
compatible=("60524", "64659", "Presta 97200"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RectIn:
|
||||||
|
left: float
|
||||||
|
top: float
|
||||||
|
width: float
|
||||||
|
height: float
|
||||||
|
|
||||||
|
@property
|
||||||
|
def right(self) -> float:
|
||||||
|
return self.left + self.width
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bottom(self) -> float:
|
||||||
|
return self.top + self.height
|
||||||
|
|
||||||
|
@property
|
||||||
|
def area(self) -> float:
|
||||||
|
return self.width * self.height
|
||||||
|
|
||||||
|
def contains(self, other: RectIn, slop: float = 0.03) -> bool:
|
||||||
|
return (
|
||||||
|
other.left >= self.left - slop
|
||||||
|
and other.top >= self.top - slop
|
||||||
|
and other.right <= self.right + slop
|
||||||
|
and other.bottom <= self.bottom + slop
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DetectedLayout:
|
||||||
|
label_width_in: float
|
||||||
|
label_height_in: float
|
||||||
|
columns: int
|
||||||
|
rows: int
|
||||||
|
labels_per_sheet: int
|
||||||
|
left_margin_in: float
|
||||||
|
top_margin_in: float
|
||||||
|
horizontal_gap_in: float
|
||||||
|
vertical_gap_in: float
|
||||||
|
safe_inset_in: float
|
||||||
|
print_to_edge: bool
|
||||||
|
snapped_bleed: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class PrintAreaError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def lookup_known_product(product_id: str) -> KnownProduct | None:
|
||||||
|
return KNOWN_PRODUCTS.get((product_id or "").strip())
|
||||||
|
|
||||||
|
|
||||||
|
def product_id_from_name(name: str) -> str:
|
||||||
|
digits = "".join(ch for ch in name if ch.isdigit())
|
||||||
|
if "60504" in name:
|
||||||
|
return "60504"
|
||||||
|
if "22827" in name:
|
||||||
|
return "22827"
|
||||||
|
return digits[:8]
|
||||||
|
|
||||||
|
|
||||||
|
def recommended_safe_inset_in(
|
||||||
|
*,
|
||||||
|
safe_inset_in: float = 0.0,
|
||||||
|
print_to_edge: bool = False,
|
||||||
|
) -> float:
|
||||||
|
if safe_inset_in > 0:
|
||||||
|
return safe_inset_in
|
||||||
|
if print_to_edge:
|
||||||
|
return DEFAULT_PRINT_TO_EDGE_INSET_IN
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def detect_label_layout(
|
||||||
|
raw_rects: Sequence[tuple[float, float, float, float]],
|
||||||
|
page_width_in: float,
|
||||||
|
page_height_in: float,
|
||||||
|
*,
|
||||||
|
marketed_width_in: float | None = None,
|
||||||
|
marketed_height_in: float | None = None,
|
||||||
|
print_to_edge: bool = False,
|
||||||
|
default_safe_inset_in: float = 0.0,
|
||||||
|
) -> DetectedLayout:
|
||||||
|
"""
|
||||||
|
Choose the die-cut grid from mixed Word/PDF guides.
|
||||||
|
|
||||||
|
Empty input, page-border-only input, and grids that cannot be formed
|
||||||
|
raise PrintAreaError.
|
||||||
|
"""
|
||||||
|
candidates = _usable_rects(raw_rects, page_width_in, page_height_in)
|
||||||
|
if not candidates:
|
||||||
|
raise PrintAreaError(
|
||||||
|
"No label rectangle shapes found in the template.\n"
|
||||||
|
"Avery blanks usually include Rectangle guides for each label."
|
||||||
|
)
|
||||||
|
|
||||||
|
cluster = _pick_die_cut_cluster(
|
||||||
|
candidates,
|
||||||
|
marketed_width_in=marketed_width_in,
|
||||||
|
marketed_height_in=marketed_height_in,
|
||||||
|
)
|
||||||
|
snapped = False
|
||||||
|
if marketed_width_in and marketed_height_in:
|
||||||
|
snapped_cluster, snapped = _snap_bleed_to_marketed(
|
||||||
|
cluster, marketed_width_in, marketed_height_in
|
||||||
|
)
|
||||||
|
if snapped:
|
||||||
|
cluster = snapped_cluster
|
||||||
|
|
||||||
|
layout = _grid_from_rects(cluster, page_width_in, page_height_in)
|
||||||
|
inset = _detect_nested_inset(cluster, candidates)
|
||||||
|
if inset <= 0:
|
||||||
|
inset = recommended_safe_inset_in(
|
||||||
|
safe_inset_in=default_safe_inset_in,
|
||||||
|
print_to_edge=print_to_edge,
|
||||||
|
)
|
||||||
|
return DetectedLayout(
|
||||||
|
**layout,
|
||||||
|
safe_inset_in=round(inset, 4),
|
||||||
|
print_to_edge=print_to_edge,
|
||||||
|
snapped_bleed=snapped,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _usable_rects(
|
||||||
|
raw_rects: Sequence[tuple[float, float, float, float]],
|
||||||
|
page_width_in: float,
|
||||||
|
page_height_in: float,
|
||||||
|
) -> list[RectIn]:
|
||||||
|
out: list[RectIn] = []
|
||||||
|
for item in raw_rects:
|
||||||
|
left, top, width, height = item
|
||||||
|
if width < _MIN_LABEL_IN or height < _MIN_LABEL_IN:
|
||||||
|
continue
|
||||||
|
if width > page_width_in * _PAGE_BORDER_FRAC and height > page_height_in * _PAGE_BORDER_FRAC:
|
||||||
|
continue
|
||||||
|
if width > page_width_in + 0.05 or height > page_height_in + 0.05:
|
||||||
|
continue
|
||||||
|
out.append(RectIn(float(left), float(top), float(width), float(height)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _size_key(rect: RectIn) -> tuple[float, float]:
|
||||||
|
return (
|
||||||
|
round(rect.width / _SIZE_BIN_IN) * _SIZE_BIN_IN,
|
||||||
|
round(rect.height / _SIZE_BIN_IN) * _SIZE_BIN_IN,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_die_cut_cluster(
|
||||||
|
rects: Sequence[RectIn],
|
||||||
|
*,
|
||||||
|
marketed_width_in: float | None,
|
||||||
|
marketed_height_in: float | None,
|
||||||
|
) -> list[RectIn]:
|
||||||
|
groups: dict[tuple[float, float], list[RectIn]] = {}
|
||||||
|
for rect in rects:
|
||||||
|
groups.setdefault(_size_key(rect), []).append(rect)
|
||||||
|
|
||||||
|
scored: list[tuple[tuple, list[RectIn]]] = []
|
||||||
|
for (width_key, height_key), group in groups.items():
|
||||||
|
columns, rows = _grid_counts(group)
|
||||||
|
grid_ok = columns * rows == len(group)
|
||||||
|
if marketed_width_in and marketed_height_in:
|
||||||
|
size_delta = abs(width_key - marketed_width_in) + abs(
|
||||||
|
height_key - marketed_height_in
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
size_delta = 0.0
|
||||||
|
# Regular grid first, then closest to marketed size, then more cells,
|
||||||
|
# then larger panels (die-cut over inner safe-area boxes).
|
||||||
|
score = (
|
||||||
|
grid_ok,
|
||||||
|
-size_delta,
|
||||||
|
len(group),
|
||||||
|
width_key * height_key,
|
||||||
|
)
|
||||||
|
scored.append((score, group))
|
||||||
|
|
||||||
|
scored.sort(key=lambda item: item[0], reverse=True)
|
||||||
|
return list(scored[0][1])
|
||||||
|
|
||||||
|
|
||||||
|
def _grid_counts(rects: Sequence[RectIn]) -> tuple[int, int]:
|
||||||
|
xs = {_bin_pos(r.left) for r in rects}
|
||||||
|
ys = {_bin_pos(r.top) for r in rects}
|
||||||
|
return max(1, len(xs)), max(1, len(ys))
|
||||||
|
|
||||||
|
|
||||||
|
def _bin_pos(value: float) -> float:
|
||||||
|
return round(value / _POS_BIN_IN) * _POS_BIN_IN
|
||||||
|
|
||||||
|
|
||||||
|
def _snap_bleed_to_marketed(
|
||||||
|
rects: Sequence[RectIn],
|
||||||
|
marketed_width_in: float,
|
||||||
|
marketed_height_in: float,
|
||||||
|
) -> tuple[list[RectIn], bool]:
|
||||||
|
"""Shrink oversized bleed guides toward the published die-cut. Never expand."""
|
||||||
|
width = median(r.width for r in rects)
|
||||||
|
height = median(r.height for r in rects)
|
||||||
|
extra_w = width - marketed_width_in
|
||||||
|
extra_h = height - marketed_height_in
|
||||||
|
snap_w = _BLEED_SNAP_MIN_IN <= extra_w <= _BLEED_SNAP_MAX_IN
|
||||||
|
snap_h = _BLEED_SNAP_MIN_IN <= extra_h <= _BLEED_SNAP_MAX_IN
|
||||||
|
if not snap_w and not snap_h:
|
||||||
|
return list(rects), False
|
||||||
|
|
||||||
|
snapped: list[RectIn] = []
|
||||||
|
for rect in rects:
|
||||||
|
left, top, w, h = rect.left, rect.top, rect.width, rect.height
|
||||||
|
if snap_w:
|
||||||
|
left += (w - marketed_width_in) / 2.0
|
||||||
|
w = marketed_width_in
|
||||||
|
if snap_h:
|
||||||
|
top += (h - marketed_height_in) / 2.0
|
||||||
|
h = marketed_height_in
|
||||||
|
snapped.append(RectIn(left, top, w, h))
|
||||||
|
return snapped, True
|
||||||
|
|
||||||
|
|
||||||
|
def _grid_from_rects(
|
||||||
|
rects: Sequence[RectIn],
|
||||||
|
page_width_in: float,
|
||||||
|
page_height_in: float,
|
||||||
|
) -> dict[str, float | int]:
|
||||||
|
if not rects:
|
||||||
|
raise PrintAreaError("No label rectangles remain after filtering.")
|
||||||
|
ordered = sorted(rects, key=lambda r: (_bin_pos(r.top), _bin_pos(r.left)))
|
||||||
|
xs_actual: dict[float, list[float]] = {}
|
||||||
|
ys_actual: dict[float, list[float]] = {}
|
||||||
|
for rect in ordered:
|
||||||
|
xs_actual.setdefault(_bin_pos(rect.left), []).append(rect.left)
|
||||||
|
ys_actual.setdefault(_bin_pos(rect.top), []).append(rect.top)
|
||||||
|
xs = sorted(xs_actual)
|
||||||
|
ys = sorted(ys_actual)
|
||||||
|
label_w = float(median(r.width for r in ordered))
|
||||||
|
label_h = float(median(r.height for r in ordered))
|
||||||
|
left_margin = float(median(xs_actual[xs[0]]))
|
||||||
|
top_margin = float(median(ys_actual[ys[0]]))
|
||||||
|
h_gap = (float(median(xs_actual[xs[1]])) - left_margin - label_w) if len(xs) >= 2 else 0.0
|
||||||
|
v_gap = (float(median(ys_actual[ys[1]])) - top_margin - label_h) if len(ys) >= 2 else 0.0
|
||||||
|
columns = max(1, len(xs))
|
||||||
|
rows = max(1, len(ys))
|
||||||
|
if left_margin < -0.05 or top_margin < -0.05:
|
||||||
|
raise PrintAreaError("Detected label origin is off the page.")
|
||||||
|
if left_margin + columns * label_w > page_width_in + 0.15:
|
||||||
|
raise PrintAreaError("Detected label grid is wider than the page.")
|
||||||
|
if top_margin + rows * label_h > page_height_in + 0.15:
|
||||||
|
raise PrintAreaError("Detected label grid is taller than the page.")
|
||||||
|
return {
|
||||||
|
"label_width_in": label_w,
|
||||||
|
"label_height_in": label_h,
|
||||||
|
"columns": columns,
|
||||||
|
"rows": rows,
|
||||||
|
"labels_per_sheet": columns * rows,
|
||||||
|
"left_margin_in": left_margin,
|
||||||
|
"top_margin_in": top_margin,
|
||||||
|
"horizontal_gap_in": max(0.0, h_gap),
|
||||||
|
"vertical_gap_in": max(0.0, v_gap),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _mean_inset(outer: RectIn, inner: RectIn) -> float:
|
||||||
|
return (
|
||||||
|
(inner.left - outer.left)
|
||||||
|
+ (inner.top - outer.top)
|
||||||
|
+ (outer.right - inner.right)
|
||||||
|
+ (outer.bottom - inner.bottom)
|
||||||
|
) / 4.0
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_nested_inset(outers: Sequence[RectIn], all_rects: Sequence[RectIn]) -> float:
|
||||||
|
insets: list[float] = []
|
||||||
|
for outer in outers:
|
||||||
|
inners = [
|
||||||
|
rect
|
||||||
|
for rect in all_rects
|
||||||
|
if rect is not outer
|
||||||
|
and outer.contains(rect)
|
||||||
|
and rect.width < outer.width - 0.04
|
||||||
|
and rect.height < outer.height - 0.04
|
||||||
|
]
|
||||||
|
if not inners:
|
||||||
|
continue
|
||||||
|
inner = max(inners, key=lambda r: r.area)
|
||||||
|
inset = _mean_inset(outer, inner)
|
||||||
|
if 0.04 <= inset <= 0.45:
|
||||||
|
insets.append(inset)
|
||||||
|
if len(insets) < max(1, len(outers) // 2):
|
||||||
|
return 0.0
|
||||||
|
return float(median(insets))
|
||||||
|
|
||||||
|
|
||||||
|
def apply_known_product_hints(data: dict) -> dict:
|
||||||
|
"""Fill print-to-edge metadata and shrink leftover bleed boxes to the die-cut."""
|
||||||
|
product = lookup_known_product(str(data.get("id", "")))
|
||||||
|
if product is None:
|
||||||
|
return data
|
||||||
|
updated = dict(data)
|
||||||
|
if not updated.get("name") or updated.get("name") == updated.get("id"):
|
||||||
|
updated["name"] = product.name
|
||||||
|
if not updated.get("marketed_size"):
|
||||||
|
updated["marketed_size"] = product.marketed_size
|
||||||
|
if not updated.get("source_url"):
|
||||||
|
updated["source_url"] = product.source_url
|
||||||
|
if not updated.get("compatible"):
|
||||||
|
updated["compatible"] = list(product.compatible)
|
||||||
|
if not updated.get("print_to_edge"):
|
||||||
|
updated["print_to_edge"] = product.print_to_edge
|
||||||
|
if float(updated.get("safe_inset_in") or 0.0) <= 0 and product.default_safe_inset_in:
|
||||||
|
updated["safe_inset_in"] = product.default_safe_inset_in
|
||||||
|
if product.print_to_edge:
|
||||||
|
_shrink_stored_bleed(updated, product)
|
||||||
|
return updated
|
||||||
|
|
||||||
|
|
||||||
|
def _shrink_stored_bleed(data: dict, product: KnownProduct) -> None:
|
||||||
|
"""Fix already-installed JSON that stored Avery bleed guides as the label."""
|
||||||
|
width = float(data.get("label_width_in") or 0.0)
|
||||||
|
height = float(data.get("label_height_in") or 0.0)
|
||||||
|
extra_w = width - product.marketed_width_in
|
||||||
|
extra_h = height - product.marketed_height_in
|
||||||
|
if _BLEED_SNAP_MIN_IN <= extra_w <= _BLEED_SNAP_MAX_IN:
|
||||||
|
data["left_margin_in"] = float(data.get("left_margin_in") or 0.0) + extra_w / 2.0
|
||||||
|
data["horizontal_gap_in"] = float(data.get("horizontal_gap_in") or 0.0) + extra_w
|
||||||
|
data["label_width_in"] = product.marketed_width_in
|
||||||
|
if _BLEED_SNAP_MIN_IN <= extra_h <= _BLEED_SNAP_MAX_IN:
|
||||||
|
data["top_margin_in"] = float(data.get("top_margin_in") or 0.0) + extra_h / 2.0
|
||||||
|
data["vertical_gap_in"] = float(data.get("vertical_gap_in") or 0.0) + extra_h
|
||||||
|
data["label_height_in"] = product.marketed_height_in
|
||||||
@@ -27,6 +27,8 @@ class LabelTemplate:
|
|||||||
product_group: str = "U-0651-01"
|
product_group: str = "U-0651-01"
|
||||||
marketed_size: str = '4" x 4"'
|
marketed_size: str = '4" x 4"'
|
||||||
print_to_edge: bool = False
|
print_to_edge: bool = False
|
||||||
|
# Inset from the die-cut to the recommended print area (0 = none / unknown)
|
||||||
|
safe_inset_in: float = 0.0
|
||||||
compatible: tuple[str, ...] = ("60524", "64659", "Presta 97200")
|
compatible: tuple[str, ...] = ("60524", "64659", "Presta 97200")
|
||||||
|
|
||||||
page_width_in: float = 8.5
|
page_width_in: float = 8.5
|
||||||
@@ -123,10 +125,22 @@ class LabelTemplate:
|
|||||||
lines.append(f"Source file: {self.source_file}")
|
lines.append(f"Source file: {self.source_file}")
|
||||||
if self.source_url:
|
if self.source_url:
|
||||||
lines.append(f"URL: {self.source_url}")
|
lines.append(f"URL: {self.source_url}")
|
||||||
|
if self.print_to_edge:
|
||||||
|
lines.append("Print-to-edge: yes (keep text inside the safe print area)")
|
||||||
|
if self.safe_inset_in > 0:
|
||||||
|
lines.append(f"Safe print inset: {self.safe_inset_in:.3f}\"")
|
||||||
if self.compatible:
|
if self.compatible:
|
||||||
lines.append(f"Compatible: {', '.join(self.compatible)}")
|
lines.append(f"Compatible: {', '.join(self.compatible)}")
|
||||||
return lines
|
return lines
|
||||||
|
|
||||||
|
def recommended_safe_inset_in(self) -> float:
|
||||||
|
from .print_area import recommended_safe_inset_in as _recommended
|
||||||
|
|
||||||
|
return _recommended(
|
||||||
|
safe_inset_in=self.safe_inset_in,
|
||||||
|
print_to_edge=self.print_to_edge,
|
||||||
|
)
|
||||||
|
|
||||||
def to_dict(self) -> dict[str, Any]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
d = asdict(self)
|
d = asdict(self)
|
||||||
d["compatible"] = list(self.compatible)
|
d["compatible"] = list(self.compatible)
|
||||||
@@ -134,6 +148,9 @@ class LabelTemplate:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, data: dict[str, Any]) -> LabelTemplate:
|
def from_dict(cls, data: dict[str, Any]) -> LabelTemplate:
|
||||||
|
from .print_area import apply_known_product_hints
|
||||||
|
|
||||||
|
data = apply_known_product_hints(data)
|
||||||
compat = data.get("compatible", ())
|
compat = data.get("compatible", ())
|
||||||
if isinstance(compat, list):
|
if isinstance(compat, list):
|
||||||
compat = tuple(compat)
|
compat = tuple(compat)
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ import shutil
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from .app_paths import user_templates_dir
|
from .app_paths import user_templates_dir
|
||||||
|
from .print_area import (
|
||||||
|
PrintAreaError,
|
||||||
|
detect_label_layout,
|
||||||
|
lookup_known_product,
|
||||||
|
product_id_from_name,
|
||||||
|
)
|
||||||
from .template_60504 import AVERY_60504, LabelTemplate, set_active_template
|
from .template_60504 import AVERY_60504, LabelTemplate, set_active_template
|
||||||
|
|
||||||
SUPPORTED_TEMPLATE_EXT = {".json", ".doc", ".docx", ".pdf"}
|
SUPPORTED_TEMPLATE_EXT = {".json", ".doc", ".docx", ".pdf"}
|
||||||
@@ -81,45 +87,15 @@ def measure_word_template(path: Path) -> LabelTemplate:
|
|||||||
if width >= 0.5 and height >= 0.5:
|
if width >= 0.5 and height >= 0.5:
|
||||||
rects.append((left, top, width, height))
|
rects.append((left, top, width, height))
|
||||||
|
|
||||||
if len(rects) < 1:
|
|
||||||
raise TemplateLoadError(
|
|
||||||
"No label rectangle shapes found in the Word template.\n"
|
|
||||||
"Avery blanks usually include Rectangle guides for each label."
|
|
||||||
)
|
|
||||||
|
|
||||||
rects.sort(key=lambda r: (round(r[1], 3), round(r[0], 3)))
|
|
||||||
xs = sorted({round(r[0], 4) for r in rects})
|
|
||||||
ys = sorted({round(r[1], 4) for r in rects})
|
|
||||||
left_margin = xs[0]
|
|
||||||
top_margin = ys[0]
|
|
||||||
label_w = rects[0][2]
|
|
||||||
label_h = rects[0][3]
|
|
||||||
h_gap = (xs[1] - xs[0] - label_w) if len(xs) >= 2 else 0.0
|
|
||||||
v_gap = (ys[1] - ys[0] - label_h) if len(ys) >= 2 else 0.0
|
|
||||||
columns = max(1, len(xs))
|
|
||||||
rows = max(1, len(ys))
|
|
||||||
|
|
||||||
stem = path.stem
|
stem = path.stem
|
||||||
digits = "".join(ch for ch in stem if ch.isdigit())
|
tpl_id = product_id_from_name(stem) or stem[:32]
|
||||||
tpl_id = digits[:8] if digits else stem[:32]
|
return _template_from_rects(
|
||||||
if "60504" in stem:
|
rects,
|
||||||
tpl_id = "60504"
|
page_w=page_w,
|
||||||
return LabelTemplate(
|
page_h=page_h,
|
||||||
id=tpl_id or "custom",
|
tpl_id=tpl_id or "custom",
|
||||||
name=f"Avery {tpl_id}" if tpl_id.isdigit() else stem,
|
|
||||||
source_file=path.name,
|
source_file=path.name,
|
||||||
page_width_in=page_w,
|
fallback_name=stem,
|
||||||
page_height_in=page_h,
|
|
||||||
label_width_in=label_w,
|
|
||||||
label_height_in=label_h,
|
|
||||||
columns=columns,
|
|
||||||
rows=rows,
|
|
||||||
labels_per_sheet=columns * rows,
|
|
||||||
left_margin_in=left_margin,
|
|
||||||
top_margin_in=top_margin,
|
|
||||||
horizontal_gap_in=max(0.0, h_gap),
|
|
||||||
vertical_gap_in=max(0.0, v_gap),
|
|
||||||
compatible=(),
|
|
||||||
)
|
)
|
||||||
except TemplateLoadError:
|
except TemplateLoadError:
|
||||||
raise
|
raise
|
||||||
@@ -167,60 +143,78 @@ def measure_pdf_template(path: Path) -> LabelTemplate:
|
|||||||
continue
|
continue
|
||||||
w = abs(r.x1 - r.x0) / 72.0
|
w = abs(r.x1 - r.x0) / 72.0
|
||||||
h = abs(r.y1 - r.y0) / 72.0
|
h = abs(r.y1 - r.y0) / 72.0
|
||||||
# Near-square label-sized panels only
|
if w >= 0.5 and h >= 0.5:
|
||||||
if 2.5 <= w <= 5.0 and 2.5 <= h <= 5.0 and abs(w - h) < 0.35:
|
|
||||||
rects.append((r.x0 / 72.0, r.y0 / 72.0, w, h))
|
rects.append((r.x0 / 72.0, r.y0 / 72.0, w, h))
|
||||||
|
|
||||||
# Deduplicate nearly-identical rects
|
|
||||||
unique: list[tuple[float, float, float, float]] = []
|
unique: list[tuple[float, float, float, float]] = []
|
||||||
for r in sorted(rects, key=lambda x: (round(x[1], 2), round(x[0], 2))):
|
for r in sorted(rects, key=lambda x: (round(x[1], 2), round(x[0], 2))):
|
||||||
if not unique or abs(r[0] - unique[-1][0]) > 0.05 or abs(r[1] - unique[-1][1]) > 0.05:
|
if not unique or abs(r[0] - unique[-1][0]) > 0.05 or abs(r[1] - unique[-1][1]) > 0.05:
|
||||||
unique.append(r)
|
unique.append(r)
|
||||||
rects = unique
|
|
||||||
|
|
||||||
if len(rects) >= 2:
|
tpl_id = product_id_from_name(path.stem) or path.stem[:32]
|
||||||
rects.sort(key=lambda r: (round(r[1], 3), round(r[0], 3)))
|
try:
|
||||||
xs = sorted({round(r[0], 3) for r in rects})
|
return _template_from_rects(
|
||||||
ys = sorted({round(r[1], 3) for r in rects})
|
unique,
|
||||||
label_w = rects[0][2]
|
page_w=page_w,
|
||||||
label_h = rects[0][3]
|
page_h=page_h,
|
||||||
h_gap = (xs[1] - xs[0] - label_w) if len(xs) > 1 else 0.0
|
tpl_id=tpl_id,
|
||||||
v_gap = (ys[1] - ys[0] - label_h) if len(ys) > 1 else 0.0
|
source_file=path.name,
|
||||||
columns = max(1, len(xs))
|
fallback_name=path.stem,
|
||||||
rows = max(1, len(ys))
|
)
|
||||||
# Reject garbage grids (Avery PDF line art often yields this)
|
except TemplateLoadError:
|
||||||
if columns * rows > 8 or (is_60504 and (columns != 2 or rows != 2)):
|
|
||||||
if is_60504:
|
if is_60504:
|
||||||
return _fallback_60504()
|
return _fallback_60504()
|
||||||
raise TemplateLoadError(
|
raise
|
||||||
"PDF label detection looked unreliable.\n"
|
|
||||||
"Please download/import the Microsoft Word (.doc) blank instead."
|
|
||||||
)
|
|
||||||
return LabelTemplate(
|
|
||||||
id="60504" if is_60504 else path.stem[:32],
|
|
||||||
name=f"Avery 60504" if is_60504 else path.stem,
|
|
||||||
source_file=path.name,
|
|
||||||
page_width_in=page_w,
|
|
||||||
page_height_in=page_h,
|
|
||||||
label_width_in=label_w,
|
|
||||||
label_height_in=label_h,
|
|
||||||
columns=columns,
|
|
||||||
rows=rows,
|
|
||||||
labels_per_sheet=columns * rows,
|
|
||||||
left_margin_in=xs[0],
|
|
||||||
top_margin_in=ys[0],
|
|
||||||
horizontal_gap_in=max(0.0, h_gap),
|
|
||||||
vertical_gap_in=max(0.0, v_gap),
|
|
||||||
compatible=(),
|
|
||||||
)
|
|
||||||
finally:
|
finally:
|
||||||
doc.close()
|
doc.close()
|
||||||
|
|
||||||
if is_60504:
|
|
||||||
return _fallback_60504()
|
def _template_from_rects(
|
||||||
raise TemplateLoadError(
|
rects: list[tuple[float, float, float, float]],
|
||||||
"Could not detect label rectangles in this PDF.\n"
|
*,
|
||||||
"Prefer Avery's Word blank template (.doc), or a measured .json template."
|
page_w: float,
|
||||||
|
page_h: float,
|
||||||
|
tpl_id: str,
|
||||||
|
source_file: str,
|
||||||
|
fallback_name: str,
|
||||||
|
) -> LabelTemplate:
|
||||||
|
known = lookup_known_product(tpl_id)
|
||||||
|
try:
|
||||||
|
layout = detect_label_layout(
|
||||||
|
rects,
|
||||||
|
page_w,
|
||||||
|
page_h,
|
||||||
|
marketed_width_in=known.marketed_width_in if known else None,
|
||||||
|
marketed_height_in=known.marketed_height_in if known else None,
|
||||||
|
print_to_edge=bool(known.print_to_edge) if known else False,
|
||||||
|
default_safe_inset_in=known.default_safe_inset_in if known else 0.0,
|
||||||
|
)
|
||||||
|
except PrintAreaError as exc:
|
||||||
|
raise TemplateLoadError(str(exc)) from exc
|
||||||
|
|
||||||
|
name = known.name if known else (
|
||||||
|
f"Avery {tpl_id}" if tpl_id.isdigit() else fallback_name
|
||||||
|
)
|
||||||
|
return LabelTemplate(
|
||||||
|
id=tpl_id or "custom",
|
||||||
|
name=name,
|
||||||
|
source_file=source_file,
|
||||||
|
source_url=known.source_url if known else "",
|
||||||
|
marketed_size=known.marketed_size if known else "",
|
||||||
|
print_to_edge=layout.print_to_edge,
|
||||||
|
safe_inset_in=layout.safe_inset_in,
|
||||||
|
compatible=known.compatible if known else (),
|
||||||
|
page_width_in=page_w,
|
||||||
|
page_height_in=page_h,
|
||||||
|
label_width_in=layout.label_width_in,
|
||||||
|
label_height_in=layout.label_height_in,
|
||||||
|
columns=layout.columns,
|
||||||
|
rows=layout.rows,
|
||||||
|
labels_per_sheet=layout.labels_per_sheet,
|
||||||
|
left_margin_in=layout.left_margin_in,
|
||||||
|
top_margin_in=layout.top_margin_in,
|
||||||
|
horizontal_gap_in=layout.horizontal_gap_in,
|
||||||
|
vertical_gap_in=layout.vertical_gap_in,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -257,6 +251,8 @@ def install_template_file(path: Path | str) -> tuple[LabelTemplate, Path]:
|
|||||||
stem = _safe_stem(tpl.id or path.stem)
|
stem = _safe_stem(tpl.id or path.stem)
|
||||||
if "60504" in path.stem or tpl.id == "60504":
|
if "60504" in path.stem or tpl.id == "60504":
|
||||||
stem = "60504"
|
stem = "60504"
|
||||||
|
elif "22827" in path.stem or tpl.id == "22827":
|
||||||
|
stem = "22827"
|
||||||
|
|
||||||
if path.parent.resolve() != dest_dir.resolve():
|
if path.parent.resolve() != dest_dir.resolve():
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
"""Print-area detection: die-cut vs bleed vs safe inset."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from avery_studio.print_area import (
|
||||||
|
DEFAULT_PRINT_TO_EDGE_INSET_IN,
|
||||||
|
PrintAreaError,
|
||||||
|
apply_known_product_hints,
|
||||||
|
detect_label_layout,
|
||||||
|
product_id_from_name,
|
||||||
|
)
|
||||||
|
from avery_studio.template_60504 import LabelTemplate
|
||||||
|
|
||||||
|
|
||||||
|
def _grid(
|
||||||
|
left: float,
|
||||||
|
top: float,
|
||||||
|
width: float,
|
||||||
|
height: float,
|
||||||
|
h_gap: float,
|
||||||
|
v_gap: float,
|
||||||
|
columns: int = 2,
|
||||||
|
rows: int = 2,
|
||||||
|
) -> list[tuple[float, float, float, float]]:
|
||||||
|
rects = []
|
||||||
|
for row in range(rows):
|
||||||
|
for col in range(columns):
|
||||||
|
rects.append(
|
||||||
|
(
|
||||||
|
left + col * (width + h_gap),
|
||||||
|
top + row * (height + v_gap),
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return rects
|
||||||
|
|
||||||
|
|
||||||
|
class DetectLabelLayoutTests(unittest.TestCase):
|
||||||
|
def test_empty_rects_raise(self) -> None:
|
||||||
|
with self.assertRaises(PrintAreaError):
|
||||||
|
detect_label_layout([], 8.5, 11.0)
|
||||||
|
|
||||||
|
def test_page_border_only_raises(self) -> None:
|
||||||
|
with self.assertRaises(PrintAreaError):
|
||||||
|
detect_label_layout([(0.0, 0.0, 8.5, 11.0)], 8.5, 11.0)
|
||||||
|
|
||||||
|
def test_60504_guides_are_not_snapped_outward(self) -> None:
|
||||||
|
rects = _grid(0.251, 1.001, 3.937, 3.937, 0.125, 1.126)
|
||||||
|
layout = detect_label_layout(
|
||||||
|
rects,
|
||||||
|
8.5,
|
||||||
|
11.0,
|
||||||
|
marketed_width_in=4.0,
|
||||||
|
marketed_height_in=4.0,
|
||||||
|
print_to_edge=False,
|
||||||
|
)
|
||||||
|
self.assertAlmostEqual(layout.label_width_in, 3.937, places=3)
|
||||||
|
self.assertAlmostEqual(layout.label_height_in, 3.937, places=3)
|
||||||
|
self.assertEqual(layout.columns, 2)
|
||||||
|
self.assertEqual(layout.rows, 2)
|
||||||
|
self.assertFalse(layout.snapped_bleed)
|
||||||
|
self.assertEqual(layout.safe_inset_in, 0.0)
|
||||||
|
|
||||||
|
def test_22827_picks_die_cut_and_nested_safe_inset(self) -> None:
|
||||||
|
bleed = _grid(0.625, 0.50, 3.75, 5.00, 0.00, 0.25)
|
||||||
|
die = _grid(0.75, 0.625, 3.50, 4.75, 0.00, 0.25)
|
||||||
|
# Distinct from the 0.125" print-to-edge default so we know it was measured.
|
||||||
|
safe = [(left + 0.1875, top + 0.1875, 3.125, 4.375) for left, top, _w, _h in die]
|
||||||
|
junk = [(0.15, 0.12, 1.2, 0.55), (0.0, 0.0, 8.5, 11.0)]
|
||||||
|
layout = detect_label_layout(
|
||||||
|
bleed + die + safe + junk,
|
||||||
|
8.5,
|
||||||
|
11.0,
|
||||||
|
marketed_width_in=3.5,
|
||||||
|
marketed_height_in=4.75,
|
||||||
|
print_to_edge=True,
|
||||||
|
default_safe_inset_in=DEFAULT_PRINT_TO_EDGE_INSET_IN,
|
||||||
|
)
|
||||||
|
self.assertAlmostEqual(layout.label_width_in, 3.5, places=3)
|
||||||
|
self.assertAlmostEqual(layout.label_height_in, 4.75, places=3)
|
||||||
|
self.assertEqual((layout.columns, layout.rows), (2, 2))
|
||||||
|
self.assertAlmostEqual(layout.left_margin_in, 0.75, places=3)
|
||||||
|
self.assertAlmostEqual(layout.top_margin_in, 0.625, places=3)
|
||||||
|
self.assertAlmostEqual(layout.horizontal_gap_in, 0.0, places=3)
|
||||||
|
self.assertAlmostEqual(layout.vertical_gap_in, 0.25, places=3)
|
||||||
|
self.assertAlmostEqual(layout.safe_inset_in, 0.1875, places=3)
|
||||||
|
self.assertTrue(layout.print_to_edge)
|
||||||
|
|
||||||
|
def test_22827_bleed_only_snaps_to_marketed_and_uses_default_inset(self) -> None:
|
||||||
|
bleed = _grid(0.625, 0.50, 3.75, 5.00, 0.00, 0.25)
|
||||||
|
layout = detect_label_layout(
|
||||||
|
bleed,
|
||||||
|
8.5,
|
||||||
|
11.0,
|
||||||
|
marketed_width_in=3.5,
|
||||||
|
marketed_height_in=4.75,
|
||||||
|
print_to_edge=True,
|
||||||
|
default_safe_inset_in=DEFAULT_PRINT_TO_EDGE_INSET_IN,
|
||||||
|
)
|
||||||
|
self.assertTrue(layout.snapped_bleed)
|
||||||
|
self.assertAlmostEqual(layout.label_width_in, 3.5, places=3)
|
||||||
|
self.assertAlmostEqual(layout.label_height_in, 4.75, places=3)
|
||||||
|
self.assertAlmostEqual(layout.left_margin_in, 0.75, places=3)
|
||||||
|
self.assertAlmostEqual(layout.top_margin_in, 0.625, places=3)
|
||||||
|
# Adjacent 3.75" bleed boxes shrink toward their centers → 0.25" gutter.
|
||||||
|
self.assertAlmostEqual(layout.horizontal_gap_in, 0.25, places=3)
|
||||||
|
self.assertAlmostEqual(layout.vertical_gap_in, 0.50, places=3)
|
||||||
|
self.assertAlmostEqual(layout.safe_inset_in, 0.125, places=3)
|
||||||
|
|
||||||
|
def test_22827_overlapping_bleed_keeps_zero_horizontal_gap(self) -> None:
|
||||||
|
# Print-to-edge 3.5" labels that touch: bleed 3.75" at pitch 3.5" (overlap).
|
||||||
|
bleed = _grid(0.625, 0.50, 3.75, 5.00, -0.25, 0.00)
|
||||||
|
layout = detect_label_layout(
|
||||||
|
bleed,
|
||||||
|
8.5,
|
||||||
|
11.0,
|
||||||
|
marketed_width_in=3.5,
|
||||||
|
marketed_height_in=4.75,
|
||||||
|
print_to_edge=True,
|
||||||
|
default_safe_inset_in=DEFAULT_PRINT_TO_EDGE_INSET_IN,
|
||||||
|
)
|
||||||
|
self.assertTrue(layout.snapped_bleed)
|
||||||
|
self.assertAlmostEqual(layout.label_width_in, 3.5, places=3)
|
||||||
|
self.assertAlmostEqual(layout.horizontal_gap_in, 0.0, places=3)
|
||||||
|
self.assertAlmostEqual(layout.left_margin_in, 0.75, places=3)
|
||||||
|
|
||||||
|
def test_unknown_product_uses_larger_grid_not_inner_boxes(self) -> None:
|
||||||
|
outer = _grid(0.75, 0.625, 3.50, 4.75, 0.00, 0.25)
|
||||||
|
inner = [
|
||||||
|
(left + 0.20, top + 0.20, 3.10, 4.35) for left, top, _w, _h in outer
|
||||||
|
]
|
||||||
|
layout = detect_label_layout(outer + inner, 8.5, 11.0)
|
||||||
|
self.assertAlmostEqual(layout.label_width_in, 3.50, places=3)
|
||||||
|
self.assertAlmostEqual(layout.label_height_in, 4.75, places=3)
|
||||||
|
self.assertGreater(layout.safe_inset_in, 0.1)
|
||||||
|
|
||||||
|
|
||||||
|
class ProductHintTests(unittest.TestCase):
|
||||||
|
def test_product_id_from_filename(self) -> None:
|
||||||
|
self.assertEqual(product_id_from_name("Avery22827_Blank.doc"), "22827")
|
||||||
|
self.assertEqual(product_id_from_name("Avery60504UltraDuty.doc"), "60504")
|
||||||
|
|
||||||
|
def test_22827_json_gets_safe_inset_without_changing_near_die_cut(self) -> None:
|
||||||
|
data = apply_known_product_hints(
|
||||||
|
{
|
||||||
|
"id": "22827",
|
||||||
|
"label_width_in": 3.51,
|
||||||
|
"label_height_in": 4.76,
|
||||||
|
"left_margin_in": 0.74,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertTrue(data["print_to_edge"])
|
||||||
|
self.assertEqual(data["safe_inset_in"], DEFAULT_PRINT_TO_EDGE_INSET_IN)
|
||||||
|
self.assertEqual(data["label_width_in"], 3.51)
|
||||||
|
self.assertEqual(data["left_margin_in"], 0.74)
|
||||||
|
self.assertEqual(data["marketed_size"], '3.5" x 4.75"')
|
||||||
|
|
||||||
|
def test_22827_json_bleed_boxes_shrink_to_die_cut(self) -> None:
|
||||||
|
data = apply_known_product_hints(
|
||||||
|
{
|
||||||
|
"id": "22827",
|
||||||
|
"label_width_in": 3.75,
|
||||||
|
"label_height_in": 5.00,
|
||||||
|
"left_margin_in": 0.625,
|
||||||
|
"top_margin_in": 0.50,
|
||||||
|
"horizontal_gap_in": 0.0,
|
||||||
|
"vertical_gap_in": 0.25,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertAlmostEqual(data["label_width_in"], 3.5)
|
||||||
|
self.assertAlmostEqual(data["label_height_in"], 4.75)
|
||||||
|
self.assertAlmostEqual(data["left_margin_in"], 0.75)
|
||||||
|
self.assertAlmostEqual(data["top_margin_in"], 0.625)
|
||||||
|
self.assertAlmostEqual(data["horizontal_gap_in"], 0.25)
|
||||||
|
self.assertAlmostEqual(data["vertical_gap_in"], 0.50)
|
||||||
|
|
||||||
|
def test_label_template_from_dict_applies_22827_hints(self) -> None:
|
||||||
|
tpl = LabelTemplate.from_dict({"id": "22827", "label_width_in": 3.5, "label_height_in": 4.75})
|
||||||
|
self.assertTrue(tpl.print_to_edge)
|
||||||
|
self.assertAlmostEqual(tpl.recommended_safe_inset_in(), 0.125)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user