feat: a ready sheet can carry the empty strips cut from its top and bottom, and prints without them
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 7m49s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m23s

Step 1 of trimming empty strips (Marcus, 2026-11-18): the server side.

- ProductionSource has trim_top_cm and trim_bottom_cm (default 0); only
  a measured finished sheet may carry them, and length_cm is what is
  left, billed and printed.
- The generator leaves those file rows out (whole decode and banded PNG
  reading), and the proportion check compares the art with what is left.
  A PDF with a cut, or a cut that does not match the file, goes to hand
  preparation.
- The Prumo report says "Faixas vazias cortadas: N cm".

The Site does not send the cut yet (step 2).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-18 11:44:48 -03:00
parent ad3a966ae2
commit 06f4ec9f20
6 changed files with 120 additions and 6 deletions

View File

@@ -101,7 +101,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage -v run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage -v
- name: Runtime and retention regressions - name: Runtime and retention regressions
run: | run: |

View File

@@ -127,6 +127,11 @@ class ProductionSource(StrictModel):
rotation_degrees: Literal[0, 90] = 0 rotation_degrees: Literal[0, 90] = 0
mirrored: bool = False mirrored: bool = False
measurement: Literal['file', 'customer'] measurement: Literal['file', 'customer']
# The fully transparent strips the Site cut from the top and the bottom of
# a ready sheet (Marcus, 2026-11-18): length_cm is what is left, billed
# and printed; the file itself is length_cm plus both trims long.
trim_top_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
trim_bottom_cm: Decimal = Field(default=Decimal(0), ge=0, le=6000)
class ProductionPlacement(StrictModel): class ProductionPlacement(StrictModel):
source_index: int = Field(ge=0, le=199, strict=True) source_index: int = Field(ge=0, le=199, strict=True)
@@ -224,6 +229,8 @@ class Item(StrictModel):
raise ValueError('Production source does not fit the selected product') raise ValueError('Production source does not fit the selected product')
if is_sheet and (source.rotation_degrees or source.mirrored): if is_sheet and (source.rotation_degrees or source.mirrored):
raise ValueError('Finished sheets cannot be rotated or mirrored by the layout') raise ValueError('Finished sheets cannot be rotated or mirrored by the layout')
if (source.trim_top_cm or source.trim_bottom_cm) and (not is_sheet or source.measurement != 'file'):
raise ValueError('Only a measured finished sheet has its empty strips cut')
# A textile transfer is pressed face down: mirrored, it prints backwards. # A textile transfer is pressed face down: mirrored, it prints backwards.
if self.mode == 'avulsa' and source.mirrored: if self.mode == 'avulsa' and source.mirrored:
raise ValueError('Textile artwork cannot be mirrored') raise ValueError('Textile artwork cannot be mirrored')

View File

@@ -226,6 +226,8 @@ class Source:
def __init__(self, path, name): def __init__(self, path, name):
self.path, self.name = path, name self.path, self.name = path, name
# File rows left out at the top and the bottom (trim()).
self.cut = (0, 0)
with open(path, 'rb') as handle: with open(path, 'rb') as handle:
head = handle.read(1024) head = handle.read(1024)
self.pdf = b'%PDF-' in head self.pdf = b'%PDF-' in head
@@ -268,6 +270,23 @@ class Source:
pass pass
image.close() image.close()
def trim(self, spec):
"""Leave out the empty strips the Site cut from a ready sheet's top and
bottom (Marcus, 2026-11-18). From then on `size` is what is printed."""
top_cm = Decimal(str(spec.get('trim_top_cm') or 0))
bottom_cm = Decimal(str(spec.get('trim_bottom_cm') or 0))
if not (top_cm or bottom_cm):
return
if self.pdf:
raise Unsupported(f'"{self.name}": o corte das faixas vazias só vale para imagens')
full_cm = Decimal(str(spec['length_cm'])) + top_cm + bottom_cm
width, height = self.size
top, bottom = round(height * top_cm / full_cm), round(height * bottom_cm / full_cm)
if top + bottom >= height:
raise Unsupported(f'"{self.name}": o corte das faixas vazias tiraria o arquivo inteiro')
self.cut = (top, bottom)
self.size = (width, height - top - bottom)
def decoded(self, width, height): def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA.""" """The whole file at (width, height) px, upright, RGBA."""
if self.pdf: if self.pdf:
@@ -325,7 +344,15 @@ class Piece:
key = (id(self.source), self.rotation, self.mirrored, self.w, self.h) key = (id(self.source), self.rotation, self.mirrored, self.w, self.h)
if key not in cache: if key not in cache:
upright = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h) upright = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
image = self.source.decoded(*upright) top, bottom = self.source.cut
if top or bottom:
# A trimmed sheet (never turned): the file at the piece's scale,
# then the rows between the strips.
scale = self.h / self.source.size[1]
image = self.source.decoded(self.w, max(1, round((self.source.size[1] + top + bottom) * scale)))
image = image.crop((0, round(top * scale), self.w, round(top * scale) + self.h))
else:
image = self.source.decoded(*upright)
if self.mirrored: if self.mirrored:
image = ImageOps.mirror(image) image = ImageOps.mirror(image)
if self.rotation: if self.rotation:
@@ -349,10 +376,13 @@ class Piece:
self.reader = PngRows(self.source.path) self.reader = PngRows(self.source.path)
self.buffer, self.buffer_top = None, 0 self.buffer, self.buffer_top = None, 0
sw, sh = self.reader.width, self.reader.height sw, sh = self.reader.width, self.reader.height
per_row = sh / self.h # A trimmed sheet starts `skip` file rows down and stops `cut` rows short.
skip, cut = self.source.cut
per_row = (sh - skip - cut) / self.h
# The source rows behind [a, b), with room for the filter on each side. # The source rows behind [a, b), with room for the filter on each side.
margin = 0 if per_row == 1 and sw == self.w else math.ceil(3 * max(per_row, 1)) + 2 margin = 0 if per_row == 1 and sw == self.w else math.ceil(3 * max(per_row, 1)) + 2
want_top, want_bottom = max(0, math.floor(a * per_row) - margin), min(sh, math.ceil(b * per_row) + margin) want_top = max(0, math.floor(a * per_row) + skip - margin)
want_bottom = min(sh, math.ceil(b * per_row) + skip + margin)
while self.buffer_top + (self.buffer.height if self.buffer else 0) < want_bottom: while self.buffer_top + (self.buffer.height if self.buffer else 0) < want_bottom:
band = rgba(self.reader.band(BAND_ROWS)) band = rgba(self.reader.band(BAND_ROWS))
if self.buffer is None: if self.buffer is None:
@@ -366,8 +396,8 @@ class Piece:
self.buffer = self.buffer.crop((0, want_top - self.buffer_top, sw, self.buffer.height)) self.buffer = self.buffer.crop((0, want_top - self.buffer_top, sw, self.buffer.height))
self.buffer_top = want_top self.buffer_top = want_top
if per_row == 1 and sw == self.w: if per_row == 1 and sw == self.w:
return self.buffer.crop((0, a - self.buffer_top, sw, b - self.buffer_top)) return self.buffer.crop((0, a + skip - self.buffer_top, sw, b + skip - self.buffer_top))
box = (0, a * per_row - self.buffer_top, sw, b * per_row - self.buffer_top) box = (0, a * per_row + skip - self.buffer_top, sw, b * per_row + skip - self.buffer_top)
return self.buffer.resize((self.w, b - a), Image.LANCZOS, box=box) return self.buffer.resize((self.w, b - a), Image.LANCZOS, box=box)
def close(self): def close(self):
@@ -455,6 +485,8 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
raise Unsupported('o item usa uma montagem antiga') raise Unsupported('o item usa uma montagem antiga')
sources = [Source(*files[index]) for index in range(len(production['sources']))] sources = [Source(*files[index]) for index in range(len(production['sources']))]
try: try:
for spec, source in zip(production['sources'], sources):
source.trim(spec)
vector = {index for index, source in enumerate(sources) if source.pdf} vector = {index for index, source in enumerate(sources) if source.pdf}
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm)) lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
width = px(production['film_width_cm']) width = px(production['film_width_cm'])

View File

@@ -103,6 +103,11 @@ def report(order, uploads):
lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, ' lines.append(f'{lead}{len(placements)} arte{"s" if len(placements) != 1 else ""}, '
f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), ' f'{rotated} girada{"s" if rotated != 1 else ""} (couberam melhor), '
f'altura {_cm(production.get("height_cm"))} cm') f'altura {_cm(production.get("height_cm"))} cm')
# The empty strips the Site cut from a ready sheet (Marcus, 2026-11-18).
trimmed = sum(Decimal(str(s.get('trim_top_cm') or 0)) + Decimal(str(s.get('trim_bottom_cm') or 0))
for s in production.get('sources') or [])
if trimmed:
lines.append(f'{lead}Faixas vazias cortadas: {_cm(trimmed)} cm')
billed = item.get('billed_metres') or item.get('metres') billed = item.get('billed_metres') or item.get('metres')
if billed: if billed:
lines.append(f'{lead}Cobrado {_m(billed)} m (height_cm {_cm(production.get("height_cm"))})') lines.append(f'{lead}Cobrado {_m(billed)} m (height_cm {_cm(production.get("height_cm"))})')

View File

@@ -115,6 +115,26 @@ class PngRenderTests(unittest.TestCase):
self.assertGreater(film.crop((0, 59, film.width, film.height)).getextrema()[3][1], 0) self.assertGreater(film.crop((0, 59, film.width, film.height)).getextrema()[3][1], 0)
self.assertEqual(detail['format'], 'png') self.assertEqual(detail['format'], 'png')
def test_a_trimmed_sheet_prints_only_what_is_between_its_empty_strips(self):
# The Site cut 1 cm of transparency above and below 0,5 cm of art
# (Marcus, 2026-11-18): the film is the art alone, read whole or in bands.
art = quadrants(118, 59, alpha=True)
sheet = Image.new('RGBA', (118, 118 + 59 + 118))
sheet.paste(art, (0, 118))
spec = item([placement(0, 0, 1, 0.5)], [{**source(1, 0.5), 'kind': 'sheet',
'trim_top_cm': 1, 'trim_bottom_cm': 1}], 0.5)
for stream in (False, True):
with mock.patch.object(printpng, 'STREAM_ABOVE_PIXELS', 0 if stream else 10 ** 9):
parts, detail = self.render(spec, [self.save(sheet, 'trimmed.png')])
film = Image.open(parts[0][0])
self.assertEqual(film.size, (px(57), 59), stream)
self.assertEqual(film.crop((0, 0, 118, 59)).tobytes(), art.tobytes(), stream)
self.assertEqual(detail['height_cm'], '0.5')
# A cut that does not match the file is refused, so the room prepares it.
spec['production']['sources'][0].update(trim_top_cm=2, trim_bottom_cm=2)
with self.assertRaises(printpng.Unsupported):
self.render(spec, [self.save(sheet, 'trimmed.png')])
def test_loose_art_is_turned_and_mirrored_like_the_site(self): def test_loose_art_is_turned_and_mirrored_like_the_site(self):
art = quadrants(80, 40, alpha=True) art = quadrants(80, 40, alpha=True)
# 80 x 40 px at 300 DPI is 6,773 x 3,387 cm; placed turned 90 degrees. # 80 x 40 px at 300 DPI is 6,773 x 3,387 cm; placed turned 90 degrees.

50
tests/test_sheet_trim.py Normal file
View File

@@ -0,0 +1,50 @@
"""Empty strips cut from a ready sheet (Marcus, 2026-11-18): only a measured
finished sheet may carry them, and they never change what is placed.
Run from the repository root: python3 -m unittest tests.test_sheet_trim -v.
"""
import unittest
from uuid import uuid4
from pydantic import ValidationError
from app.core.models import Item
def sheet_item(mode='file', kind='sheet', measurement='file', top=10, bottom=40):
upload = str(uuid4())
width = 27 if mode in ('uvfile', 'uv') else 57
return {'mode': mode, 'metres': '4.6', 'grade': 100, 'uploads': [upload],
'quality_status': 'ok', 'quality_acknowledged': False,
'production': {'version': 3, 'film_width_cm': width, 'height_cm': '453.8',
'sources': [{'upload_id': upload, 'kind': kind, 'width_cm': width,
'length_cm': '453.8', 'copies': 1, 'measurement': measurement,
'trim_top_cm': top, 'trim_bottom_cm': bottom}],
'placements': [{'source_index': 0, 'copy_index': 0, 'x_cm': 0, 'y_cm': 0,
'width_cm': width, 'length_cm': '453.8',
'rotation_degrees': 0, 'mirrored': False}]}}
class SheetTrimTests(unittest.TestCase):
def test_a_measured_ready_sheet_carries_its_cut_strips(self):
item = Item.model_validate(sheet_item(mode='uvfile'))
source = item.production.sources[0]
self.assertEqual((source.trim_top_cm, source.trim_bottom_cm), (10, 40))
def test_no_strips_by_default(self):
data = sheet_item()
del data['production']['sources'][0]['trim_top_cm'], data['production']['sources'][0]['trim_bottom_cm']
source = Item.model_validate(data).production.sources[0]
self.assertEqual((source.trim_top_cm, source.trim_bottom_cm), (0, 0))
def test_only_a_measured_ready_sheet_is_trimmed(self):
with self.assertRaises(ValidationError):
Item.model_validate(sheet_item(measurement='customer'))
with self.assertRaises(ValidationError):
Item.model_validate(sheet_item(mode='avulsa', kind='artwork'))
with self.assertRaises(ValidationError):
Item.model_validate(sheet_item(top=-1))
if __name__ == '__main__':
unittest.main()