Skip to content
Open
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
6 changes: 6 additions & 0 deletions app/labeldesigner/cable_flag.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ def flag_strip(half: Image.Image, wrap: int, dpi: int, along: bool) -> Image.Ima
return strip.transpose(Image.Transpose.ROTATE_270)


def flag_size(size: tuple, wrap: int, along: bool) -> tuple[int, int]:
"""The size of the flag flag_strip() makes of a label of size."""
width, height = size
return (2 * width + wrap, height) if along else (width, 2 * height + wrap)


def flag_box(box: list, size: tuple, wrap: int, along: bool) -> list:
"""Where box [x0, y0, x1, y1] on a label of size is on the second label
of the flag flag_strip() makes of it."""
Expand Down
40 changes: 26 additions & 14 deletions app/labeldesigner/label.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .enums import LabelContent, LabelOrientation, LabelType
from . import codes, icons
from .cable_flag import flag_box, flag_strip
from .cable_flag import flag_box, flag_size, flag_strip
from app.fonts import EMOJI_FONT_PATH, font_info, has_glyphs
from .dates import LANGUAGES as DATE_LANGUAGES, format_date
import os
Expand Down Expand Up @@ -921,12 +921,13 @@ def _generate(self):
along = self._label_orientation == LabelOrientation.ROTATED
half = img.size
img = flag_strip(img, self._flag_wrap, self._flag_dpi, along)
check_image_size(*img.size)
# Its parts are on both labels
self.parts += [dict(part, box=flag_box(part['box'], half, self._flag_wrap, along)) for part in self.parts]
return img.rotate(180) if self.turned else img

def _generate_label(self):
def _generate_label(self, drawn: bool = True):
"""The label drawn. Not drawn, it is laid out and refused as drawing
it refuses it, see check()."""
# Process possible templates in the text and the code
self.process_templates()
# A preview shows a code of the blanks still to fill in, printed it
Expand Down Expand Up @@ -1126,6 +1127,21 @@ def across(name):

logger.debug(f"Image resolution: {width} x {height} px")
check_image_size(width, height)
# A cable flag is the label twice and the part around the cable
if self._flag_wrap:
check_image_size(*flag_size((width, height), self._flag_wrap, self._label_orientation == LabelOrientation.ROTATED))
# Calculate border rectangle (inside the image, respecting thickness)
rect = [self._border_distance[0],
self._border_distance[1],
width - self._border_distance[0] - 1,
height - self._border_distance[1] - 1]
# Validity checks on rect:
# - x1 >= x0
# - y1 >= y0
if self._border_thickness > 0 and (rect[2] < rect[0] or rect[3] < rect[1]):
raise ValueError("Invalid border rectangle")
if not drawn:
return None
imgResult = Image.new('RGB', (width, height), 'white')

if img is not None:
Expand All @@ -1140,17 +1156,6 @@ def across(name):
# Draw border if thickness > 0
if self._border_thickness > 0:
draw = ImageDraw.Draw(imgResult)
# Calculate border rectangle (inside the image, respecting thickness)
rect = [self._border_distance[0],
self._border_distance[1],
imgResult.width - self._border_distance[0] - 1,
imgResult.height - self._border_distance[1] - 1]
# Validity checks on rect:
# - x1 >= x0
# - y1 >= y0
if rect[2] < rect[0] or rect[3] < rect[1]:
raise ValueError("Invalid border rectangle")

# Draw (rounded) rectangle
draw.rounded_rectangle(rect, radius=self._border_roundness, outline=self._border_color, width=self._border_thickness)
# Left and right swapped as the text reads, the preview shows it so
Expand Down Expand Up @@ -1285,6 +1290,13 @@ def _crop_image_to_content(img: Image.Image) -> Image.Image:
return img
return img.crop(bbox)

def check(self) -> None:
"""Raise what drawing the label raises, e.g. for a value that is none
of the choices of its blank, a wrong check digit or a label too
large, without drawing it: it is laid out as drawn, its code made
once, for the drawing as well."""
self._generate_label(drawn=False)

def _generate_barcode(self):
# An unknown type is refused before the value is looked at
barcode_class = codes.barcode_class(self.barcode_type)
Expand Down
65 changes: 63 additions & 2 deletions app/labeldesigner/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
"fields": {
"$ref": "#/components/schemas/BlankSettings"
},
"list": {
"type": "string",
"description": "A list as `/labeldesigner/api/print` takes it: the preview shows its first line, `X-Label-Sheet`, `{{total}}` and the whole sheet count all its labels, `X-List-Filled` tells the blanks every line fills. More than `PRINT_MAX_COUNT` labels are refused."
},
"mark_blanks": {
"type": "string",
"enum": [
Expand Down Expand Up @@ -123,6 +127,10 @@
"fields": {
"$ref": "#/components/schemas/BlankSettings"
},
"list": {
"type": "string",
"description": "A list as `/labeldesigner/api/print` takes it: the preview shows its first line, `X-Label-Sheet`, `{{total}}` and the whole sheet count all its labels, `X-List-Filled` tells the blanks every line fills. More than `PRINT_MAX_COUNT` labels are refused."
},
"mark_blanks": {
"type": "string",
"enum": [
Expand Down Expand Up @@ -194,6 +202,12 @@
"type": "string"
}
},
"X-List-Filled": {
"description": "With `list` on a label with blanks, those every line of it fills, as JSON, e.g. `[\"Name\"]`. The label designer asks for the others.",
"schema": {
"type": "string"
}
},
"X-PDF-Pages": {
"description": "Number of pages of an uploaded PDF.",
"schema": {
Expand Down Expand Up @@ -291,11 +305,26 @@
}
},
"400": {
"description": "Invalid parameters, e.g. \"Font size is required\".",
"description": "Invalid parameters, e.g. \"Font size is required\". `of` is `list` where the `list` is refused rather than the label, e.g. for more labels than `PRINT_MAX_COUNT`.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Result"
"allOf": [
{
"$ref": "#/components/schemas/Result"
},
{
"type": "object",
"properties": {
"of": {
"type": "string",
"enum": [
"list"
]
}
}
}
]
}
}
}
Expand Down Expand Up @@ -858,6 +887,9 @@
},
"fields": {
"$ref": "#/components/schemas/BlankSettings"
},
"list": {
"$ref": "#/components/schemas/PrintList"
}
}
},
Expand Down Expand Up @@ -925,6 +957,9 @@
},
"fields": {
"$ref": "#/components/schemas/BlankSettings"
},
"list": {
"$ref": "#/components/schemas/PrintList"
}
}
},
Expand Down Expand Up @@ -2900,6 +2935,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
},
"list": {
"$ref": "#/components/schemas/PrintList"
}
}
},
Expand Down Expand Up @@ -2973,6 +3011,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
},
"list": {
"$ref": "#/components/schemas/PrintList"
}
}
},
Expand Down Expand Up @@ -3443,6 +3484,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
},
"list": {
"$ref": "#/components/schemas/PrintList"
}
}
}
Expand Down Expand Up @@ -3506,6 +3550,9 @@
},
"blanks": {
"$ref": "#/components/schemas/SavedLabelBlanks"
},
"list": {
"$ref": "#/components/schemas/PrintList"
}
}
},
Expand Down Expand Up @@ -4027,6 +4074,20 @@
}
},
"schemas": {
"PrintList": {
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
],
"description": "One label for each line, e.g. names pasted from a spreadsheet. The cells of a line, split at tabs, fill the blanks of the label in order, those of the text, then those of a code it draws; a label without blanks takes them as its lines of text, each with its settings. A cell is inserted as it is, its templates are none. An empty cell is not given: its blank keeps its value of `blanks` or its default, its line its text, as do those beyond the cells; cells beyond them are left out. Pasted from a spreadsheet, with tabs and a cell that starts with a quote, cells it quotes, e.g. `\"5\"\" pot\"` or one with a line break, are read as it writes them; another list keeps its quotes. A count at the end of a line, in its last cell after a word without digits, e.g. `Basil x 20`, `Basil x20` or `Basil X 20`, prints it that many times; `M3 x 10`, `Box 2 x 3` or a cell of `x 5` alone print once, as written. Each line prints its count times `print_count` labels in a row, each of every file and PDF page as `collate` orders them; `{{counter}}` counts all labels of the list and `{{total}}` is their number. On sheets of labels they fill the labels in order. Empty lines are left out, a list without lines prints as without it. In a JSON body also a list of its lines, any other value, e.g. null, is refused. More than `PRINT_MAX_COUNT` labels are refused, and so is the whole list where one of its lines is, e.g. with a value that is none of the choices of its blank."
},
"ScanRequest": {
"type": "object",
"required": ["name", "code"],
Expand Down
75 changes: 75 additions & 0 deletions app/labeldesigner/print_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""A list printed as labels, one for each line, e.g. plant names pasted from
a spreadsheet. The cells of a line, split at tabs, fill the label in order,
a count at its end prints it that many times."""

import csv
import io
import re

# A count at the end of a cell after a word, e.g. "Basil x 20", "Basil x20"
# or "Basil X 20"
COUNT = re.compile(r'(?s)(.*\S)\s+[xX]\s*(\d+)\s*')
# More digits make more labels than any job takes
COUNT_DIGITS = 9

NO_PLACE = 'Add text or a blank to the label to print a list'
NOT_TEXT = 'list must be a text or a list of texts'


class Refused(ValueError):
"""A list refused, not the label it is printed on."""


def too_many(most: int) -> str:
"""The refusal of a list of more than most labels."""
return f'A list prints at most {most} labels. Split it.'


def _rows(text: str) -> list[list[str]]:
"""The cells of each line, split at tabs. A spreadsheet quotes a cell
with quotes or line breaks, e.g. "5"" pot": where a cell starts with a
quote and all read so, they are read as it writes them. Typed, e.g.
"Best" tomatoes, or a quote left open, a list keeps its quotes."""
lines = [line.split('\t') for line in text.splitlines()]
if any(cell.startswith('"') for cells in lines for cell in cells):
try:
return list(csv.reader(io.StringIO(text, newline=''), dialect='excel-tab', strict=True))
except csv.Error:
# E.g. a quote left open, or a cell longer than any line of a label
pass
return lines


def _counted(cells: list[str], most: int) -> tuple[list[str], int]:
"""The cells of a line without its count and the count, else 1. Only a
count in the last cell after a word without digits counts: "M3 x 10",
"Box 2 x 3" or a cell of "x 5" alone are names, printed once."""
counted = COUNT.fullmatch(cells[-1])
digits = counted.group(2).lstrip('0') if counted else ''
if not digits or any(char.isdigit() for char in counted.group(1).split()[-1]):
return cells, 1
return cells[:-1] + [counted.group(1)], int(digits) if len(digits) <= COUNT_DIGITS else most + 1


def parse(text, most: int) -> list[tuple[list[str], int]]:
"""The lines of a list, text or its lines as a JSON body gives them: the
cells of each and the labels it prints. Empty lines are left out, and
so are empty cells at the end. Refused for another value, e.g. null,
and where they print more than most labels."""
if isinstance(text, list) and all(isinstance(line, str) for line in text):
text = '\n'.join(text)
if not isinstance(text, str):
raise Refused(NOT_TEXT)
lines, labels = [], 0
for row in _rows(text):
cells = [cell.strip() for cell in row]
while cells and not cells[-1]:
cells.pop()
if not cells:
continue
cells, count = _counted(cells, most)
labels += count
if labels > most:
raise Refused(too_many(most))
lines.append((cells, count))
return lines
6 changes: 4 additions & 2 deletions app/labeldesigner/refusals.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from pdf2image.exceptions import PDFInfoNotInstalledError, PDFPageCountError, PDFPopplerTimeoutError, PDFSyntaxError
from PIL import Image

from . import adding, ipp, scan, sheets
from . import adding, ipp, print_list, scan, sheets
from .cable_flag import CABLE_DIAMETER_REFUSED, CABLE_FLAG_REFUSED
from .codes import BARCODE_TOO_LONG, TYPES as BARCODE_TYPES, check_digit_problems, code_problems
from .label import (LETTER_SPACING_REFUSED, MAX_BLANK_CHOICE_LENGTH, MAX_BLANK_CHOICES, MAX_COUNTER_START_LENGTH, MAX_COUNTER_STEP, MAX_IMAGE_SCALING_FACTOR,
Expand Down Expand Up @@ -135,6 +135,8 @@
OTHER_LABEL,
SAME_NUMBERS,
'print_count must be greater than 0',
print_list.NO_PLACE,
print_list.NOT_TEXT,
*sorted({sheets.start_problem(sheets.per_sheet(label)) for label in LABELS if sheets.is_paper(label)}),
*check_digit_problems(),
*code_problems(),
Expand Down Expand Up @@ -211,7 +213,7 @@ def _limits() -> tuple:
max_count = current_app.config['PRINT_MAX_COUNT']
# At least a whole sheet of labels
counts = sorted({max_count} | {sheets.per_sheet(label) for label in LABELS if sheets.is_paper(label) and sheets.per_sheet(label) > max_count})
return (tuple(f'print_count must not exceed {count}' for count in counts),
return (tuple(f'print_count must not exceed {count}' for count in counts) + tuple(print_list.too_many(count) for count in counts),
tuple((re.compile(rf'(?s)A print job must not have more than {count} labels, .*'), f'A print job must not have more than {count} labels')
for count in counts))

Expand Down
Loading