Files
dtf-system/app/printpng.py
Cauê Faleiros bb6fb14b1a
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
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
fix: the server refuses stacked pieces and files laid out at other proportions, and never cuts a strip with ink
The price came from the layout the browser sent, checked only in part:
- Pieces on top of each other passed: 100 copies stacked in one place bill
  10 cm and print over each other. The layout validator now refuses any
  overlap.
- A file laid out at proportions it does not have (a 5 m sheet sent as
  10 cm) was found only by the print file, after payment. The quote now
  checks each raster file's proportions from the bytes it already reads.
- The empty strips the Site cuts from a ready sheet were cut on its word.
  The print file now reads them: a strip with ink sends the item to hand
  preparation with the reason, instead of printing the art cut off.

Test fixtures that laid real images out at impossible proportions now keep
the image's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:56:00 -03:00

792 lines
36 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The print file as a PNG (Dropstar's third round, item 13, 2026-10-29).
FlexiPRINT's Spot OK 1 preset makes the white underbase from transparency, and
it reads that reliably only from a PNG: the montador writes each order item as
a 300 DPI PNG with an alpha channel on a transparent background, the same file
from payment to Finalizado. The customer may still send PNG or PDF; the output
is always PNG, and nothing converts it afterwards.
A 57 cm x 15 m sheet is 6732 x 177165 px, 4,7 GB as pixels, so nothing here
holds a whole sheet: the film is composed and written in bands of rows.
- Writing: each band is encoded by Pillow without compression, which still
chooses each row's PNG filter, and its filtered rows go into one zlib stream
for the whole file.
- A long PNG sheet is read band by band the same way backwards: the next
band's compressed rows, behind the last decoded row unfiltered, are wrapped
as a small PNG of their own that Pillow decodes.
- A PDF page is rendered band by band at 300 DPI by PDFium, vector all the way.
- Loose artwork is small: each file is decoded, turned and scaled to its place
once, and copied into every band it crosses.
A layout longer than a part leaves as parts of up to PART_CM, 10 m since
Marcus's 18/11 answer (Flexi opens up to 4 GB per image; Dropstar,
2026-10-30, was 15 m), DTF-7-item-1-p3.png, each with its footer saying which part it
is. Loose artwork is cut where no piece crosses; a finished sheet between
copies, or else in a clear band of its own pixels, and through the artwork
only when it has none (#136).
"""
import io
import math
import os
import struct
import zlib
from decimal import Decimal
from PIL import Image, ImageDraw, ImageFont, ImageOps
from .core.models import PRODUCTION_VERSIONS
from .printfile import (FOOTER_CM, FOOTER_LOGO, FOOTER_LOGO_CM, MAX_DECODED_PIXELS, SUPPORTED_FORMATS,
Unsupported, check_layout)
from .printtiles import Pyramid
DPI = 300
PX_PER_CM = DPI / 2.54
# Parts of up to 10 m (Marcus, 2026-11-18): a 15 m part, 6732 x 177165 px, is
# 4,8 GB decoded and FlexiPRINT refuses it. PRINT_PART_CM overrides it.
PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1000'))
# A cut through artwork only when no gap between pieces is this close to the limit.
CUT_SEARCH_CM = Decimal('200')
BAND_ROWS = 512
# A pixel above this alpha takes ink (web/site-sheet.js ALFA_TINTA).
INK_ALPHA = 10
# Above this a source is read band by band instead of decoded whole.
STREAM_ABOVE_PIXELS = 40_000_000
FOOTER_TEXT_CM = 1.1
Image.MAX_IMAGE_PIXELS = None
def px(cm):
return int(round(float(cm) * PX_PER_CM))
# ---- Writing ----------------------------------------------------------------
def _chunk(fp, kind, data):
fp.write(struct.pack('>I', len(data)) + kind + data)
fp.write(struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff))
class PngWriter:
"""An RGBA PNG written band by band: only one band is ever in memory."""
def __init__(self, fp, width, height):
self.fp, self.width, self.height = fp, width, height
self.rows = 0
# Level 1 and no row filter: the same size as Pillow's filters at
# level 6, in under half the time. #81's 91,5 m took 6 hours (2026-11-25).
self.z = zlib.compressobj(1)
self.pending = []
fp.write(b'\x89PNG\r\n\x1a\n')
_chunk(fp, b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0))
per_metre = round(DPI / 0.0254)
_chunk(fp, b'pHYs', struct.pack('>IIB', per_metre, per_metre, 1))
def band(self, image):
"""Append `image` (RGBA, the film's width) below what is written."""
if image.mode != 'RGBA' or image.width != self.width:
raise ValueError('a band must be RGBA and as wide as the film')
rows = image.height
if self.rows + rows > self.height:
raise ValueError('more rows than the file has')
raw, stride = image.tobytes(), 4 * self.width
# Each row behind its filter byte, 0 (none).
self._write(b''.join(b'\x00' + raw[i * stride:(i + 1) * stride] for i in range(rows)))
self.rows += rows
def _write(self, data):
out = self.z.compress(data)
if out:
self.pending.append(out)
if sum(map(len, self.pending)) >= 1 << 20:
self._flush()
def _flush(self):
if self.pending:
_chunk(self.fp, b'IDAT', b''.join(self.pending))
self.pending = []
def close(self):
if self.rows != self.height:
raise ValueError(f'{self.rows} of {self.height} rows written')
self.pending.append(self.z.flush())
self._flush()
_chunk(self.fp, b'IEND', b'')
# ---- Reading ----------------------------------------------------------------
class PngRows:
"""A PNG's rows in order, band by band, without decoding the whole image.
Only 8-bit, non-interlaced files: anything else is decoded whole.
"""
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
def __init__(self, path):
self.fp = open(path, 'rb')
if self.fp.read(8) != b'\x89PNG\r\n\x1a\n':
raise Unsupported('o PNG está corrompido')
self.extra = []
while True:
size, kind = struct.unpack('>I4s', self.fp.read(8))
if kind == b'IDAT':
self.idat_left = size
break
data = self.fp.read(size)
self.fp.read(4)
if kind == b'IHDR':
self.width, self.height, depth, color, _, _, interlace = struct.unpack('>IIBBBBB', data)
self.ihdr = data
if depth != 8 or interlace or color not in self.CHANNELS:
raise Unsupported('PNG de 16 bits ou entrelaçado')
self.row_bytes = 1 + self.width * self.CHANNELS[color]
elif kind in (b'PLTE', b'tRNS'):
self.extra.append((kind, data))
elif kind == b'IEND':
raise Unsupported('o PNG não tem imagem')
self.inflate = zlib.decompressobj()
self.buffer = b''
self.done = 0 # rows decoded so far
self.previous = None # the last decoded row, raw
def _compressed(self, want):
"""At least `want` bytes of filtered rows, unless the file ends first."""
parts, have = [self.buffer], len(self.buffer)
while have < want:
if not self.idat_left:
self.fp.read(4)
size, kind = struct.unpack('>I4s', self.fp.read(8))
if kind != b'IDAT':
break
self.idat_left = size
block = self.fp.read(min(self.idat_left, 1 << 20))
self.idat_left -= len(block)
out = self.inflate.decompress(block)
parts.append(out)
have += len(out)
data = b''.join(parts)
self.buffer = data[want:]
return data[:want]
def band(self, rows):
"""The next `rows` rows (fewer at the end) as an image in the file's mode."""
rows = min(rows, self.height - self.done)
if rows <= 0:
return None
filtered = self._compressed(rows * self.row_bytes)
if len(filtered) != rows * self.row_bytes:
raise Unsupported('o PNG terminou antes da última linha')
lead = 1 if self.previous is not None else 0
out = io.BytesIO()
out.write(b'\x89PNG\r\n\x1a\n')
_chunk(out, b'IHDR', struct.pack('>II', self.width, rows + lead) + self.ihdr[8:])
for kind, data in self.extra:
_chunk(out, kind, data)
body = (b'\x00' + self.previous if lead else b'') + filtered
_chunk(out, b'IDAT', zlib.compress(body, 0))
_chunk(out, b'IEND', b'')
out.seek(0)
image = Image.open(out)
image.load()
if lead:
image = image.crop((0, 1, self.width, rows + 1))
self.previous = image.crop((0, rows - 1, self.width, rows)).tobytes()
self.done += rows
return image
def close(self):
self.fp.close()
def rgba(image):
if image.mode == 'RGBA':
return image
if image.mode in ('I;16', 'I;16B', 'I;16L', 'I'):
image = image.convert('I').point(lambda value: value * (1 / 257)).convert('L')
return image.convert('RGBA')
class Source:
"""One customer file: its size as the Site measured it, and its pixels."""
def __init__(self, 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:
head = handle.read(1024)
self.pdf = b'%PDF-' in head
if self.pdf:
import pypdfium2
try:
self.document = pypdfium2.PdfDocument(path)
except Exception as exc:
raise Unsupported(f'"{name}" não é um PDF que o gerador consiga ler') from exc
if len(self.document) != 1:
count = len(self.document)
self.document.close()
raise Unsupported(f'"{name}" tem {count} páginas; só PDFs de uma página são gerados automaticamente')
self.page = self.document[0]
self.size = self.page.get_size() # as displayed, /Rotate applied
self.streamable = True
return
try:
image = Image.open(path)
except Exception as exc:
raise Unsupported(f'"{name}" não é uma imagem que o gerador consiga ler') from exc
if image.format not in SUPPORTED_FORMATS:
raise Unsupported(f'"{name}" está em {image.format or "formato desconhecido"}; '
'só JPEG, PNG, WebP, TIFF e PDF são gerados automaticamente')
# Pillow decodes a whole PNG to look for EXIF after the pixels; only
# an orientation ahead of them is read, as is a JPEG's.
try:
self.orientation = (image.getexif().get(0x0112, 1)
if image.format != 'PNG' or 'exif' in image.info else 1)
except Exception:
self.orientation = 1
width, height = image.size
self.size = (height, width) if self.orientation in (5, 6, 7, 8) else (width, height)
self.streamable = False
if image.format == 'PNG' and self.orientation == 1:
try:
PngRows(path).close()
self.streamable = True
except Unsupported:
pass
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._require_clear(top, bottom)
self.cut = (top, bottom)
self.size = (width, height - top - bottom)
def _require_clear(self, top, bottom):
"""The strips the Site measured as empty must be: cut on a measure the
file does not bear out, artwork would leave the print unseen. A pixel
takes ink above INK_ALPHA, as the Site counts it. Not clear, or too
big to read here: the item goes to hand preparation, with the reason."""
width, height = self.size
where = lambda first: 'do começo' if first else 'do fim'
def check(band, offset):
for start, stop, first in ((0, top, True), (height - bottom, height, False)):
a, b = max(start, offset), min(stop, offset + band.height)
if a < b and rgba(band.crop((0, a - offset, band.width, b - offset))).getchannel('A').getextrema()[1] > INK_ALPHA:
raise Unsupported(f'"{self.name}": a faixa que o site cortou {where(first)} do arquivo tem arte. '
'Confira o arquivo e prepare a folha à mão')
if self.streamable:
reader = PngRows(self.path)
try:
done = 0
# Read in order to the end of the bottom strip (or of the top one).
while done < (height if bottom else top):
band = reader.band(BAND_ROWS)
if done < top or done + band.height > height - bottom:
check(band, done)
done += band.height
finally:
reader.close()
return
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" é grande demais para conferir as faixas cortadas; prepare a folha à mão')
with Image.open(self.path) as image:
image = ImageOps.exif_transpose(image) if self.orientation != 1 else image
check(image, 0)
def decoded(self, width, height):
"""The whole file at (width, height) px, upright, RGBA."""
if self.pdf:
if width * height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" ficaria grande demais para montar; prepare este item à mão')
scale = width / self.size[0]
image = self.page.render(scale=scale, fill_color=(0, 0, 0, 0)).to_pil()
return rgba(image).resize((width, height), Image.LANCZOS) if image.size != (width, height) else rgba(image)
image = Image.open(self.path)
if image.width * image.height > MAX_DECODED_PIXELS:
raise Unsupported(f'"{self.name}" tem {image.width} × {image.height} px, mais do que o '
'gerador processa; prepare este item à mão')
image.load()
if self.orientation != 1:
image = ImageOps.exif_transpose(image)
image = rgba(image)
return image if image.size == (width, height) else image.resize((width, height), Image.LANCZOS)
def close(self):
if self.pdf:
self.document.close()
# ---- Pieces -----------------------------------------------------------------
class Piece:
"""One placement on the film, in pixels, able to give the rows of the film
it covers, in order."""
def __init__(self, placement, source):
self.source = source
self.x, self.y = px(placement['x_cm']), px(placement['y_cm'])
self.w = max(1, px(Decimal(str(placement['x_cm'])) + Decimal(str(placement['width_cm']))) - self.x)
self.h = max(1, px(Decimal(str(placement['y_cm'])) + Decimal(str(placement['length_cm']))) - self.y)
self.rotation = placement['rotation_degrees'] % 360
self.mirrored = placement['mirrored']
self.reader = None
@property
def streamed(self):
return (self.source.streamable and not self.rotation and not self.mirrored and
self.w * self.h > STREAM_ABOVE_PIXELS)
def rows(self, top, bottom, cache):
"""The piece's rows [top, bottom) in film coordinates, as RGBA."""
a, b = top - self.y, bottom - self.y
if not self.streamed:
return self._placed(cache).crop((0, a, self.w, b))
if self.source.pdf:
return self._pdf_rows(a, b)
return self._png_rows(a, b)
def _placed(self, cache):
"""The whole piece, turned and scaled, shared by every copy."""
key = (id(self.source), self.rotation, self.mirrored, self.w, self.h)
if key not in cache:
upright = (self.h, self.w) if self.rotation in (90, 270) else (self.w, self.h)
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:
image = ImageOps.mirror(image)
if self.rotation:
# Clockwise, as the Site turns it.
image = image.rotate(-self.rotation, expand=True)
cache[key] = image if image.size == (self.w, self.h) else image.resize((self.w, self.h), Image.LANCZOS)
return cache[key]
def _pdf_rows(self, a, b):
page_w, page_h = self.source.size
scale = self.w / page_w
top_pt, bottom_pt = a / scale, max(0.0, page_h - b / scale)
image = self.source.page.render(scale=scale, crop=(0, bottom_pt, 0, top_pt),
fill_color=(0, 0, 0, 0)).to_pil()
image = rgba(image)
return image if image.size == (self.w, b - a) else image.resize((self.w, b - a), Image.LANCZOS)
def _png_rows(self, a, b):
"""Rows [a, b) of the piece from a PNG read in order, scaled to the piece."""
if self.reader is None:
self.reader = PngRows(self.source.path)
self.buffer, self.buffer_top = None, 0
sw, sh = self.reader.width, self.reader.height
# 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.
margin = 0 if per_row == 1 and sw == self.w else math.ceil(3 * max(per_row, 1)) + 2
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:
band = rgba(self.reader.band(BAND_ROWS))
if self.buffer is None:
self.buffer = band
else:
joined = Image.new('RGBA', (sw, self.buffer.height + band.height))
joined.paste(self.buffer, (0, 0))
joined.paste(band, (0, self.buffer.height))
self.buffer = joined
if want_top > self.buffer_top: # rows no band will need again
self.buffer = self.buffer.crop((0, want_top - self.buffer_top, sw, self.buffer.height))
self.buffer_top = want_top
if per_row == 1 and sw == self.w:
return self.buffer.crop((0, a + skip - self.buffer_top, sw, b + skip - 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)
def close(self):
if self.reader:
self.reader.close()
self.reader = None
# ---- Parts and footer -------------------------------------------------------
# A cut needs this much clear film: it then falls in the middle of it.
CLEAR_CUT_CM = Decimal('0.3')
def part_cuts(production, part_cm=None, clear=None):
"""Where the film is cut into parts, in cm from its top: [0, ..., height].
A cut falls in a gap between pieces; where the layout has none, as inside
a ready sheet (one piece to it), `clear(from_cm, to_cm)` finds a clear band
in the film's own pixels, so no artwork is cut in two (Marcus, 2026-11-27,
#136). Only without one either is the cut at the part's length."""
limit = Decimal(str(part_cm or PART_CM))
height = Decimal(str(production['height_cm']))
spans = [(Decimal(str(p['y_cm'])), Decimal(str(p['y_cm'])) + Decimal(str(p['length_cm'])))
for p in production['placements']]
cuts = [Decimal(0)]
while height - cuts[-1] > limit:
start = cuts[-1]
free = [end for _, end in spans
if start + limit - CUT_SEARCH_CM <= end <= start + limit
and not any(top < end < bottom for top, bottom in spans)]
# The search never goes back past half a part: no part comes out short.
found = clear(max(start + limit / 2, start + limit - CUT_SEARCH_CM), start + limit) if clear and not free else None
cuts.append(max(free) if free else found if found and found > start else start + limit)
cuts.append(height)
return cuts
def clear_band(pieces, width, from_cm, to_cm):
"""Where to cut the film between the two, in cm, so the artwork suffers
least (Marcus, 2026-11-27, #136): the middle of the clear band of at least
CLEAR_CUT_CM nearest `to_cm`; else of the widest clear band there is (a
sheet packed edge to edge may have only 2 mm between rows); else the row
with the least ink. None when the stretch is empty of rows."""
top = px(from_cm)
ink_rows, amounts = [], []
for _, band in film_bands(pieces, top, px(to_cm), width):
ink = band.getchannel('A').point(lambda a: 255 if a > 8 else 0)
ink_rows.extend(ink.getprojection()[1])
amounts.extend(ink.resize((1, ink.height), Image.BOX).tobytes())
if not ink_rows:
return None
runs, end = [], None # (length, last row, first row), clear rows only
for row in range(len(ink_rows) - 1, -2, -1):
if row >= 0 and not ink_rows[row]:
end = row if end is None else end
continue
if end is not None:
runs.append((end - row, end, row + 1))
end = None
to_cm_of = lambda row: Decimal(top + row) / Decimal(str(PX_PER_CM))
need = px(CLEAR_CUT_CM)
wide = [run for run in runs if run[0] >= need]
if wide or runs:
# runs go from the bottom up: the first wide one is the nearest the limit.
length, last, first = wide[0] if wide else max(runs, key=lambda run: (run[0], run[1]))
return to_cm_of((first + last) // 2)
least = min(amounts)
return to_cm_of(max(row for row, amount in enumerate(amounts) if amount == least))
def proof_cut(height_cm, limit_cm, fraction=None):
"""A proof's window, in cm from the film's top: `limit_cm` centred on the
thinnest stroke (fraction 0 at the top, 1 at the bottom), clamped inside
the film. Without a measured fraction it starts at the top, as before."""
height = Decimal(str(height_cm))
if height <= 0:
return [Decimal(0), Decimal(0)]
span = min(height, Decimal(str(limit_cm)))
if fraction is None:
return [Decimal(0), span]
center = min(Decimal(1), max(Decimal(0), Decimal(str(fraction)))) * height
start = min(height - span, max(Decimal(0), center - span / 2))
return [start, start + span]
def _font(size):
return ImageFont.load_default(size=size)
def footer_band(text, width):
"""The footer, 1,5 cm, black on transparent: the logo, then the line."""
height = px(FOOTER_CM)
band = Image.new('RGBA', (width, height))
draw = ImageDraw.Draw(band)
x = px(0.5)
if os.path.exists(FOOTER_LOGO):
logo = rgba(Image.open(FOOTER_LOGO))
logo_h = px(FOOTER_LOGO_CM)
logo = logo.resize((max(1, round(logo.width * logo_h / logo.height)), logo_h), Image.LANCZOS)
band.alpha_composite(logo, (x, (height - logo_h) // 2))
x += logo.width + px(0.4)
text = text.partition(' · ')[2]
room = width - x - px(0.5)
size = px(FOOTER_TEXT_CM)
while size > 10 and draw.textlength(text, font=_font(size)) > room:
size -= 4
font = _font(size)
top, bottom = font.getbbox(text)[1], font.getbbox(text)[3]
draw.text((x, (height - (bottom - top)) // 2 - top), text, font=font, fill=(0, 0, 0, 255),
stroke_width=max(1, size // 40), stroke_fill=(0, 0, 0, 255))
return band
# ---- The proof's samples ----------------------------------------------------
#
# Marcus, 2026-11-26: a proof of the finest stroke alone missed the colours
# (#100's caught only white art). The proof keeps its window on the finest
# stroke and adds short samples of the colours that window lacks, up to
# PROOF_MAX_CM in all, each apart by PROOF_GAP_CM of clear film.
PROOF_MAX_CM = Decimal('30')
PROOF_SAMPLE_CM = Decimal('5')
PROOF_GAP_CM = Decimal('1')
# Colour groups: 12 hues, then grey, white and black; 15 is no ink.
GREY, WHITE, BLACK, CLEAR = 12, 13, 14, 15
# A colour counts when it is this share of the film's ink, and is in a stretch
# when it is this share of the stretch's ink.
COLOUR_SHARE, PRESENT_SHARE = 0.02, 0.03
def colour_counts(band):
"""The band's ink by colour group, read on a copy an eighth the size."""
small = band.reduce(8) if min(band.size) >= 8 else band
alpha = small.getchannel('A')
hue, sat, val = small.convert('RGB').convert('HSV').split()
groups = hue.point(lambda h: h * 12 // 256)
achromatic = sat.point(lambda s: 255 if s < 46 else 0)
groups.paste(GREY, mask=achromatic)
groups.paste(WHITE, mask=Image.composite(val.point(lambda v: 255 if v > 217 else 0),
Image.new('L', small.size), achromatic))
groups.paste(BLACK, mask=val.point(lambda v: 255 if v < 64 else 0))
groups.paste(CLEAR, mask=alpha.point(lambda a: 255 if a < 128 else 0))
return groups.histogram()[:CLEAR]
def present(counts):
ink = sum(counts)
return {k for k, n in enumerate(counts) if ink and n >= PRESENT_SHARE * ink}
SCAN_PX_CM = 4
def film_scan(production, pictures):
"""The film's colours a centimetre at a time, [(top_cm, bottom_cm,
counts)], drawn from each file's small picture (the one the Site sends
for the Kanban, at most 480 x 720 px), so a 100 m film is read in a
moment. `pictures` maps a source index to its image bytes; a file
without one leaves its place empty."""
k = SCAN_PX_CM
film = Image.new('RGBA', (max(1, round(float(production['film_width_cm']) * k)),
max(1, round(float(production['height_cm']) * k))))
images = {}
for index, data in pictures.items():
try:
image = rgba(ImageOps.exif_transpose(Image.open(io.BytesIO(data))))
except Exception:
continue
spec = production['sources'][index]
top, bottom = (float(spec.get('trim_top_cm') or 0), float(spec.get('trim_bottom_cm') or 0))
if top or bottom:
# The picture is of the whole file: the Site cut the empty strips.
full = float(spec['length_cm']) + top + bottom
image = image.crop((0, round(image.height * top / full), image.width,
round(image.height * (full - bottom) / full)))
images[index] = image
for placement in production['placements']:
image = images.get(placement['source_index'])
if image is None:
continue
w = max(1, round(float(placement['width_cm']) * k))
h = max(1, round(float(placement['length_cm']) * k))
if placement['mirrored']:
image = ImageOps.mirror(image)
if placement['rotation_degrees'] % 360:
image = image.rotate(-placement['rotation_degrees'], expand=True)
film.alpha_composite(image.resize((w, h), Image.BOX),
(round(float(placement['x_cm']) * k), round(float(placement['y_cm']) * k)))
return [(Decimal(y) / k, Decimal(min(film.height, y + k)) / k, colour_counts(film.crop((0, y, film.width, y + k))))
for y in range(0, film.height, k)]
def proof_windows(height_cm, limit_cm, fraction, scan):
"""The proof's stretches of film, [(top, bottom)] in cm, from the top: the
finest stroke's window, then a PROOF_SAMPLE_CM sample for each colour
still missing, the most missing first. `scan` is [(top_cm, bottom_cm,
counts)] over the film."""
first = proof_cut(height_cm, limit_cm, fraction)
windows = [tuple(first)]
height = Decimal(str(height_cm))
total = sum((b - a for a, b in windows), Decimal(0))
ink = [sum(c[k] for _, _, c in scan) for k in range(CLEAR)]
wanted = {k for k, n in enumerate(ink) if sum(ink) and n >= COLOUR_SHARE * sum(ink)}
def inside(a, b):
# Only the centimetres wholly in the stretch: one on its edge may hold
# a colour the proof does not show.
return [c for top, bottom, c in scan if top >= a and bottom <= b]
covered = set().union(*(present(c) for a, b in windows for c in inside(a, b)))
while total + PROOF_GAP_CM + PROOF_SAMPLE_CM <= PROOF_MAX_CM and wanted - covered:
best = None
for top, bottom, counts in scan:
gain = (wanted - covered) & present(counts)
if not gain:
continue
centre = (top + bottom) / 2
a = min(height - PROOF_SAMPLE_CM, max(Decimal(0), centre - PROOF_SAMPLE_CM / 2)).quantize(Decimal('0.1'))
b = a + PROOF_SAMPLE_CM
if any(a < wb + PROOF_GAP_CM and b > wa - PROOF_GAP_CM for wa, wb in windows):
continue
score = (len(gain), sum(counts[k] for k in gain))
if best is None or score > best[0]:
best = (score, a, b)
if best is None:
break
_, a, b = best
windows.append((a, b))
total += PROOF_GAP_CM + (b - a)
covered |= set().union(*(present(c) for c in inside(a, b)))
return sorted(windows)
# ---- The file ---------------------------------------------------------------
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None,
proof_fraction=None, pictures=None):
"""Write the PNG part(s) of one approved order item into `out_dir`.
`files` maps each source index to (local path, original name). With
`tiles`, each part's pieces for the Kanban's viewer go in
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`,
and samples of the colours it lacks, found in `pictures` (film_scan).
Returns the parts, [(path, name)], and the evidence the Kanban shows.
"""
production = item['production']
if production.get('version') not in PRODUCTION_VERSIONS:
raise Unsupported('o item usa uma montagem antiga')
sources = [Source(*files[index]) for index in range(len(production['sources']))]
try:
for spec, source in zip(production['sources'], sources):
source.trim(spec)
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))
width = px(production['film_width_cm'])
def laid_out():
return sorted((Piece(placement, sources[placement['source_index']])
for placement in production['placements']), key=lambda piece: piece.y)
windows = None
if limit_cm:
# A proof: the finest stroke's window and samples of the other
# colours, stacked in one sheet; a normal file is cut into parts.
windows = [tuple(proof_cut(production['height_cm'], limit_cm, proof_fraction))]
if pictures and Decimal(str(production['height_cm'])) > Decimal(str(limit_cm)):
windows = proof_windows(production['height_cm'], limit_cm, proof_fraction,
film_scan(production, pictures))
cuts = [windows[0][0], windows[-1][1]]
else:
def clear(from_cm, to_cm):
# Read on pieces of its own: the film is read forward only.
scanned = laid_out()
try:
return clear_band(scanned, width, from_cm, to_cm)
finally:
for piece in scanned:
piece.close()
cuts = part_cuts(production, part_cm, clear)
pieces = laid_out()
count = len(cuts) - 1
parts, manifests = [], []
for number in range(count):
name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png'
path = os.path.join(out_dir, name)
line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else ''))
ranges = ([(px(a), px(b)) for a, b in windows] if windows
else [(px(cuts[number]), px(cuts[number + 1]))])
with open(path, 'wb') as out:
manifests.append(write_part(out, pieces, ranges, width, line,
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
parts.append((path, name))
finally:
for source in sources:
source.close()
return parts, {'format': 'png', 'dpi': DPI,
'film_width_cm': str(production['film_width_cm']),
'height_cm': str(production['height_cm']),
'width_px': width,
'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1]),
**({'tiles': manifests[i]} if manifests[i] else {})}
for i, (_, name) in enumerate(parts)],
**({'proof_windows': [[f'{Decimal(a).normalize():f}', f'{Decimal(b).normalize():f}']
for a, b in windows]} if windows else {}),
'footer': footer,
'billed_metres': str(item['billed_metres']),
'placements': len(production['placements']),
'sources': len(sources),
'vector_sources': len(vector),
'min_dpi': round(lowest) if lowest else None}
def film_bands(pieces, top, bottom, width):
"""The film's rows [top, bottom) composed, BAND_ROWS at a time: (band top,
RGBA image). Pieces are read forward only, so ranges go down the film."""
cache = {}
for band_top in range(top, bottom, BAND_ROWS):
band_bottom = min(bottom, band_top + BAND_ROWS)
band = Image.new('RGBA', (width, band_bottom - band_top))
for piece in pieces:
if piece.y >= band_bottom:
break
if piece.y + piece.h <= band_top:
continue
a, b = max(band_top, piece.y), min(band_bottom, piece.y + piece.h)
rows = piece.rows(a, b, cache)
left = max(0, -piece.x)
if left or piece.x + rows.width > width:
rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height))
band.alpha_composite(rows, (max(0, piece.x), a - band_top))
yield band_top, band
# A piece the film has passed is done with: its pixels can go.
for piece in pieces:
if piece.y + piece.h <= band_bottom:
piece.close()
live = {(id(p.source), p.rotation, p.mirrored, p.w, p.h) for p in pieces if p.y + p.h > band_bottom}
for key in [key for key in cache if key not in live]:
del cache[key]
def write_part(out, pieces, ranges, width, footer=None, tiles=None):
"""The film's rows in `ranges` [(top, bottom)], top to bottom and apart by
PROOF_GAP_CM of clear film when there are several (a proof's samples),
then the footer, as one PNG; with `tiles`, a folder, also its pieces for
the viewer. Returns their manifest."""
foot = footer_band(footer, width) if footer else None
gap = px(PROOF_GAP_CM)
height = (sum(b - a for a, b in ranges) + gap * (len(ranges) - 1) + (foot.height if foot else 0))
writer = PngWriter(out, width, height)
pyramid = None
if tiles:
def emit(level, index, data):
folder = os.path.join(tiles, str(level))
os.makedirs(folder, exist_ok=True)
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
strip.write(data)
pyramid = Pyramid(width, height, emit)
def put(band):
writer.band(band)
if pyramid:
pyramid.band(band)
for i, (top, bottom) in enumerate(ranges):
if i:
put(Image.new('RGBA', (width, gap)))
for _, band in film_bands(pieces, top, bottom, width):
put(band)
if foot:
put(foot)
writer.close()
return pyramid.close() if pyramid else None