feat: the print file is a 300 DPI PNG, in parts of up to 15 m (item 13)
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s

FlexiPRINT's Spot OK 1 makes the white from transparency and reads it
reliably only from a PNG (Dropstar's third round, item 13): each order item
is now DTF-N-item-I.png, 300 DPI, RGBA on a transparent background, with its
footer; a film over 15 m leaves as DTF-N-item-I-pK.png parts, each with
"Parte K/N" in its footer, cut between pieces of loose art when it can be.

app/printpng.py never holds a whole sheet: the film is composed and written
in bands. Pillow encodes each band (it picks the PNG filters) and one zlib
stream takes them; a long PNG sheet is read band by band by wrapping its
compressed rows as small PNGs; a PDF page is drawn band by band at 300 DPI by
PDFium (pypdfium2, a self-contained wheel); loose art is turned and scaled
once. A 57 x 220 cm sheet peaks at 191 MB, a 15 m film at 279 MB.

The parts of an item are dtf_local.print_parts (print_files.upload_id stays
the first); the board, the final approval, the folders and the cleanup see
every part, and the Kanban approves and downloads them all. A large PNG or
PDF is now generated like any other; only other large formats go to hand
preparation, and the original no longer stands in as the print file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-03 16:53:35 -03:00
parent bd1e1772a7
commit 353935bed3
12 changed files with 810 additions and 141 deletions

View File

@@ -9,7 +9,6 @@ Kanban until someone records what was done.
Run inside the API container (it needs Pillow): python -m tests.print_file_test
"""
import io
import re
import time
from urllib.request import urlopen
from uuid import uuid4
@@ -19,7 +18,19 @@ from PIL import Image
from tests.payment_test import deliver
from tests.smoke_test import Client, approved_quote as approval, upload_bytes
PT_PER_CM = 72 / 2.54
PX_PER_CM = 300 / 2.54
def px(cm):
return int(round(cm * PX_PER_CM))
def download_png(client, upload_id):
link = client.call('/operator/uploads/' + str(upload_id) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
image = Image.open(io.BytesIO(response.read()))
assert image.format == 'PNG' and image.mode == 'RGBA', (image.format, image.mode)
return image
CUSTOMER = {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': 'print-test@example.test'}
@@ -82,15 +93,16 @@ def run():
order = paid_order(client, loose_item(uid))
order, row = wait_print(client, order['id'], 'ready')
assert row['detail']['placements'] == 2 and row['detail']['min_dpi'] == round(600 / (20 / 2.54))
link = client.call('/operator/uploads/' + str(row['upload_id']) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
pdf = response.read()
assert pdf.startswith(b'%PDF-') and pdf.rstrip().endswith(b'%%EOF')
width, height = map(float, re.search(rb'/MediaBox \[0 0 ([\d.]+) ([\d.]+)\]', pdf).groups())
# The layout's 10 cm and the 1,5 cm footer band, outside the billed length.
assert abs(width - 57 * PT_PER_CM) < 0.01 and abs(height - 11.5 * PT_PER_CM) < 0.01, (width, height)
# A 300 DPI PNG on a transparent background (item 13): the layout's 10 cm
# and the 1,5 cm footer band, outside the billed length.
film = download_png(client, row['upload_id'])
assert film.size == (px(57), px(10) + px(1.5)), film.size
assert [p['name'] for p in row['parts']] == ['DTF-%d-item-1.png' % order['number']], row['parts']
for copy in range(2):
assert film.getpixel((px(20 * copy + 10), px(5))) == (220, 30, 60, 255), copy
assert film.getpixel((px(50), px(5)))[3] == 0
assert row['detail']['footer'].startswith('DROPSTAR · Pedido DTF-%d · Item 1/1 · ' % order['number']), row['detail']
print('PASS: paid order generated a 57 x 10 cm print file with both copies and its footer')
print('PASS: paid order generated a 57 x 10 cm PNG print file with both copies and its footer')
# The automatic folder, downloading on arrival, gets the generated file
# before anyone approves it; at the queue only, it does not.
@@ -140,16 +152,15 @@ def run():
'note': 'again'}, operator=True, expected=409)
print('PASS: generated file approved as final without re-uploading; order queued for printing')
# A single-page PDF is placed as a vector form, not rasterised.
# A single-page PDF is drawn from its vectors at 300 DPI.
pdf_upload = upload_bytes(client, artwork('PDF'), name='LOCAL-PRINT-TEST.pdf')
pdf_order = paid_order(client, loose_item(pdf_upload))
_, pdf_row = wait_print(client, pdf_order['id'], 'ready')
assert pdf_row['detail']['vector_sources'] == 1 and pdf_row['detail']['min_dpi'] is None, pdf_row
link = client.call('/operator/uploads/' + str(pdf_row['upload_id']) + '/download', operator=True)
with urlopen(link['url'], timeout=30) as response:
generated = response.read()
assert b'/Subtype /Form' in generated or b'/Subtype/Form' in generated
print('PASS: PDF artwork generated as a vector print file')
drawn = download_png(client, pdf_row['upload_id'])
red = drawn.getpixel((px(10), px(5)))
assert red[3] == 255 and red[0] > 200 and red[1] < 60, red
print('PASS: PDF artwork drawn into the PNG print file at 300 DPI')
# A customer cannot see or reuse another order's generated file.
other = Client()

View File

@@ -1,34 +1,9 @@
"""Large sheets: when the original is its own print file, and the format check."""
"""Large files: the format check. A large PNG or PDF sheet is read band by band
(app/printpng.py), so it no longer passes as its own print file."""
import unittest
from app.printjobs import whole_sheet
from app.scanning import check_large, format_matches, real_name
ROW = {'id': 'u1', 'name': 'folha.png', 'size': 3 * 1024 ** 3, 'scan_state': 'clean',
'purged_at': None, 'expired': False}
def sheet(**changes):
source = {'kind': 'sheet', 'width_cm': 57, 'length_cm': 500, 'copies': 1}
place = {'x_cm': 0, 'y_cm': 0, 'rotation_degrees': 0, 'mirrored': False}
for key, value in changes.items():
(source if key in source else place)[key] = value
return {'uploads': ['u1'], 'production': {'film_width_cm': 57, 'sources': [source], 'placements': [place]}}
class WholeSheetTest(unittest.TestCase):
def test_a_finished_sheet_placed_whole_is_its_own_print_file(self):
self.assertIs(whole_sheet(sheet(), {'u1': ROW}), ROW)
def test_anything_else_is_prepared_by_hand(self):
for changes in ({'copies': 2}, {'kind': 'artwork'}, {'rotation_degrees': 90}, {'mirrored': True},
{'x_cm': 1}, {'width_cm': 50}):
with self.subTest(changes=changes):
self.assertIsNone(whole_sheet(sheet(**changes), {'u1': ROW}))
self.assertIsNone(whole_sheet(sheet(), {'u1': {**ROW, 'name': 'folha.cdr'}}))
self.assertIsNone(whole_sheet(sheet(), {'u1': {**ROW, 'scan_state': 'pending'}}))
self.assertIsNone(whole_sheet(sheet(), {'u1': {**ROW, 'expired': True}}))
class FormatTest(unittest.TestCase):
def test_bytes_must_match_the_name(self):

140
tests/test_printpng.py Normal file
View File

@@ -0,0 +1,140 @@
"""The PNG print file (item 13): 300 DPI, transparent, written and read in bands.
Runs in the API image (Pillow, pikepdf, pypdfium2).
"""
import io
import os
import tempfile
import unittest
from unittest import mock
from PIL import Image
from app import printpng
from app.printpng import PngRows, PngWriter, part_cuts, px, render
from tests.test_printfile import BLUE, GREEN, RED, YELLOW, item, placement, quadrants, source
def pattern(width, height, mode='RGBA'):
"""Rows that differ from each other, so every PNG filter gets used."""
image = Image.new('RGBA', (width, height))
image.putdata([((x * 7 + y * 3) % 256, (x * y) % 256, (y * 11) % 256, 255 if (x + y) % 5 else 0)
for y in range(height) for x in range(width)])
return image if mode == 'RGBA' else image.convert(mode)
class PngStreamTests(unittest.TestCase):
def test_rows_read_in_bands_match_the_whole_image(self):
with tempfile.TemporaryDirectory() as folder:
for mode in ('RGBA', 'RGB', 'L', 'LA', 'P'):
image = pattern(61, 47, mode)
path = os.path.join(folder, mode + '.png')
image.save(path, transparency=3) if mode == 'P' else image.save(path)
reader = PngRows(path)
bands = []
while (band := reader.band(10)) is not None:
bands.append(band.convert('RGBA'))
reader.close()
whole = Image.new('RGBA', image.size)
top = 0
for band in bands:
whole.paste(band, (0, top))
top += band.height
self.assertEqual(top, 47, mode)
self.assertEqual(whole.tobytes(), Image.open(path).convert('RGBA').tobytes(), mode)
def test_bands_written_make_one_png(self):
image = pattern(53, 70)
out = io.BytesIO()
writer = PngWriter(out, 53, 70)
for top in range(0, 70, 13):
writer.band(image.crop((0, top, 53, min(70, top + 13))))
writer.close()
out.seek(0)
written = Image.open(out)
self.assertEqual([round(v) for v in written.info.get('dpi')], [300, 300])
self.assertEqual(written.convert('RGBA').tobytes(), image.tobytes())
class PngRenderTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.addCleanup(self.dir.cleanup)
def save(self, image, name):
path = os.path.join(self.dir.name, name)
image.save(path)
return path
def render(self, spec, paths, footer=None, part_cm=None):
out = os.path.join(self.dir.name, 'out')
os.makedirs(out, exist_ok=True)
files = {i: (path, os.path.basename(path)) for i, path in enumerate(paths)}
return render(spec, files, out, 'DTF-7-item-1', footer=footer, part_cm=part_cm)
def test_a_sheet_is_the_film_at_300_dpi_with_the_footer_below(self):
# 1 x 0,5 cm at 300 DPI: 118 x 59 px, on the 57 cm film.
art = quadrants(118, 59, alpha=True)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 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(art, 'sheet.png')], footer='DROPSTAR · Pedido DTF-7')
self.assertEqual([name for _, name in parts], ['DTF-7-item-1.png'])
film = Image.open(parts[0][0])
self.assertEqual(film.mode, 'RGBA')
self.assertEqual(film.size, (px(57), 59 + px(1.5)))
self.assertEqual(film.crop((0, 0, 118, 59)).tobytes(), art.tobytes(), stream)
# Transparent beside the art; the footer has ink of its own.
self.assertEqual(film.getpixel((300, 10))[3], 0)
self.assertGreater(film.crop((0, 59, film.width, film.height)).getextrema()[3][1], 0)
self.assertEqual(detail['format'], 'png')
def test_loose_art_is_turned_and_mirrored_like_the_site(self):
art = quadrants(80, 40, alpha=True)
# 80 x 40 px at 300 DPI is 6,773 x 3,387 cm; placed turned 90 degrees.
w, h = 80 / printpng.PX_PER_CM, 40 / printpng.PX_PER_CM
spec = item([placement(1, 1, h, w, rotation=90), placement(10, 1, w, h, mirrored=True, copy=1)],
[source(w, h, copies=2)], 10)
parts, _ = self.render(spec, [self.save(art, 'art.png')])
film = Image.open(parts[0][0]).convert('RGBA')
x, y = px(1), px(1)
# Turned clockwise: the top-left red goes to the top-right.
self.assertEqual(film.getpixel((x + 30, y + 10))[:3], RED)
self.assertEqual(film.getpixel((x + 10, y + 10))[:3], BLUE)
# Mirrored: green on the left.
mx = px(10)
self.assertEqual(film.getpixel((mx + 10, y + 10))[:3], GREEN)
self.assertEqual(film.getpixel((mx + 70, y + 30))[:3], BLUE)
def test_long_films_leave_as_parts_cut_between_pieces(self):
art = quadrants(118, 118, alpha=True)
placements = [placement(0, 11 * i, 10, 10, copy=i) for i in range(4)]
spec = item(placements, [source(10, 10, copies=4)], 43)
# Parts of up to 25 cm: the cut falls in the gap after the second piece, at 21 cm.
self.assertEqual([float(c) for c in part_cuts(spec['production'], 25)], [0, 21, 43])
parts, detail = self.render(spec, [self.save(art, 'art.png')], footer='DROPSTAR · Pedido DTF-7', part_cm=25)
self.assertEqual([name for _, name in parts], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png'])
first, second = (Image.open(path) for path, _ in parts)
self.assertEqual(first.height, px(21) + px(1.5))
self.assertEqual(second.height, px(43) - px(21) + px(1.5))
self.assertEqual(second.convert('RGBA').getpixel((10, px(22) - px(21) + 5))[:3], RED)
self.assertEqual([p['name'] for p in detail['parts']], ['DTF-7-item-1-p1.png', 'DTF-7-item-1-p2.png'])
def test_a_pdf_page_is_rendered_at_300_dpi(self):
art = quadrants(118, 59)
path = os.path.join(self.dir.name, 'sheet.pdf')
art.save(path, resolution=300)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 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, [path])
film = Image.open(parts[0][0]).convert('RGBA')
self.assertEqual(film.size, (px(57), 59))
# Pillow writes the PDF's image as a JPEG: close, not exact.
for point, color in (((15, 15), RED), ((100, 50), YELLOW)):
self.assertLess(max(abs(a - b) for a, b in zip(film.getpixel(point), color)), 8, point)
self.assertEqual(detail['vector_sources'], 1)
if __name__ == '__main__':
unittest.main()