Files
dtf-system/tests/test_printpng.py
Cauê Faleiros 8b7d9f0bdb
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 4m28s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m17s
feat: "Abrir e conferir", the print file full screen, in pieces (item 7)
The card's "Abrir e conferir" opens the order's print file full screen
(Dropstar's third round, item 7): zoom up to 100% real (one file pixel, one
screen pixel), the position in cm, the order's files one after the other
without closing, and the background behind the transparency light, dark or
checkered, remembered (Dropstar, 2026-10-30). Closed in Arte recebida, it asks
"Está OK?": the class of each item, prefilled with the measure, then
"Mover para Arte conferida" (the final approved, the class kept, the card
moved) or "Tratar a arte".

A 15 m film is loaded like a map: while the PNG is written, its strips of
512 rows go to storage at 100% and at each halving (app/printtiles.py,
originals/tiles/<upload>/), and the viewer (web/kanban-viewer.js) fetches
only those on screen. They go when their file expires. Storing a print file
that fails is now an attempt like a failed render, not a claim held for an
hour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:10:03 -03:00

177 lines
8.7 KiB
Python

"""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 PyramidTests(unittest.TestCase):
def test_strips_rebuild_the_film_at_each_level(self):
from app import printtiles
image = pattern(90, 1300)
strips = {}
with mock.patch.object(printtiles, 'STRIP_ROWS', 64), mock.patch.object(printtiles, 'SMALLEST_ROWS', 200):
pyramid = printtiles.Pyramid(90, 1300, lambda level, index, data: strips.setdefault(level, []).append(data))
for top in range(0, 1300, 100):
pyramid.band(image.crop((0, top, 90, min(1300, top + 100))))
manifest = pyramid.close()
self.assertEqual(len(manifest['levels']), 4) # 1300, 650, 325, 163 rows
for level, info in enumerate(manifest['levels']):
pieces = [Image.open(io.BytesIO(data)) for data in strips[level]]
self.assertEqual(len(pieces), info['strips'])
self.assertEqual(sum(p.height for p in pieces), info['height'], level)
self.assertTrue(all(p.width == info['width'] for p in pieces), level)
# Level 0 is the film itself.
whole = Image.new('RGBA', (90, 1300))
top = 0
for data in strips[0]:
piece = Image.open(io.BytesIO(data))
whole.paste(piece, (0, top))
top += piece.height
self.assertEqual(whole.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_pieces_for_the_viewer_come_with_the_file(self):
art = quadrants(118, 59, alpha=True)
spec = item([placement(0, 0, 1, 0.5)], [source(1, 0.5)], 0.5)
parts, detail = render(spec, {0: (self.save(art, 'art.png'), 'art.png')},
self.dir.name, 'DTF-7-item-1', footer='DROPSTAR · Pedido DTF-7', tiles=True)
tiles = detail['parts'][0]['tiles']
self.assertEqual((tiles['width'], tiles['height']), Image.open(parts[0][0]).size)
first = Image.open(os.path.join(self.dir.name, 'tiles', 'DTF-7-item-1.png', '0', '0.png'))
self.assertEqual(first.crop((0, 0, 118, 59)).tobytes(), art.tobytes())
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()