Some checks failed
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
The layout sees a ready sheet as one piece, so a part was cut at its length, through the artwork. Where no gap between pieces is near the limit, the film is read there: the cut falls in the middle of the nearest clear band of 3 mm, else of the widest clear band (#83's packed sheets have 2 mm between rows), else on the row with the least ink. A part is never shorter than half the limit, and the render limit allows one part more. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
231 lines
12 KiB
Python
231 lines
12 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_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):
|
|
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 sheet_spec(self, height_cm, film=10):
|
|
spec = item([placement(0, 0, film, height_cm)], [source(film, height_cm)], height_cm, film=film)
|
|
spec['production']['sources'][0]['kind'] = 'sheet'
|
|
return spec
|
|
|
|
def test_a_ready_sheet_is_cut_in_a_clear_band_not_through_the_art(self):
|
|
# Marcus, 2026-11-27, #136: one ready sheet is one piece to the layout;
|
|
# the cut finds the clear band in its pixels (30 to 31 cm) under 35 cm.
|
|
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
|
|
sheet.paste((0, 0, 0, 0), (0, px(30), px(10), px(31)))
|
|
parts, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
|
|
cut = float(detail['parts'][0]['to_cm'])
|
|
self.assertTrue(30 < cut < 31, cut)
|
|
first = Image.open(parts[0][0]).convert('RGBA')
|
|
self.assertEqual(first.getpixel((10, first.height - 2))[3], 0) # ends in the clear band
|
|
|
|
def test_a_packed_sheet_is_cut_in_its_widest_clear_band(self):
|
|
# A sheet packed edge to edge (#83: 2 mm at most between rows): the
|
|
# widest clear band, here 2 mm between dots, still cuts no ink.
|
|
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
|
|
sheet.paste((0, 0, 0, 0), (0, px(30), px(10), px(31)))
|
|
dots = [px(30 + tenth / 10) for tenth in range(1, 10, 2)] # a dot every 2 mm
|
|
for row in dots:
|
|
sheet.putpixel((px(5), row), (0, 0, 0, 255))
|
|
_, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
|
|
cut = px(float(detail['parts'][0]['to_cm']))
|
|
self.assertTrue(px(30) < cut < px(31) and cut not in dots, cut)
|
|
|
|
def test_without_any_clear_row_the_cut_takes_the_least_ink(self):
|
|
sheet = Image.new('RGBA', (px(10), px(40)), (220, 30, 60, 255))
|
|
sheet.paste((0, 0, 0, 0), (px(1), px(32), px(10), px(32) + 3)) # only a thin edge of ink there
|
|
_, detail = self.render(self.sheet_spec(40), [self.save(sheet, 'sheet.png')], part_cm=35)
|
|
self.assertTrue(px(32) <= px(float(detail['parts'][0]['to_cm'])) < px(32) + 3, detail['parts'][0])
|
|
|
|
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()
|