"""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 15 m leaves as parts of up to 15 m (Dropstar, 2026-10-30), 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 is cut between copies when it can be, and through the artwork when not. """ 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 15 m, 6732 x 177165 px (Dropstar, 2026-10-30). PART_CM = Decimal(os.environ.get('PRINT_PART_CM', '1500')) # A cut through artwork only when no gap between pieces is this close to the limit. CUT_SEARCH_CM = Decimal('200') BAND_ROWS = 512 # 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 self.previous = None # the last row written, as an image self.z = zlib.compressobj(6) 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') # The previous row on top, so each row's filter refers to the real row # above it; that first filtered row is dropped. lead = 1 if self.previous is not None else 0 framed = Image.new('RGBA', (self.width, rows + lead)) if lead: framed.paste(self.previous, (0, 0)) framed.paste(image, (0, lead)) encoded = io.BytesIO() framed.save(encoded, 'PNG', compress_level=0) filtered = zlib.decompress(_idat(encoded.getvalue())) self._write(filtered[lead * (1 + 4 * self.width):]) self.previous = image.crop((0, rows - 1, self.width, 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'') def _idat(png): """The concatenated IDAT data of an in-memory PNG.""" data, at = [], 8 while at < len(png): size, kind = struct.unpack('>I4s', png[at:at + 8]) if kind == b'IDAT': data.append(png[at + 8:at + 8 + size]) at += 12 + size return b''.join(data) # ---- 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.cut = (top, bottom) self.size = (width, height - top - bottom) 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 ------------------------------------------------------- def part_cuts(production, part_cm=None): """Where the film is cut into parts, in cm from its top: [0, ..., height].""" 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)] cuts.append(max(free) if free else start + limit) cuts.append(height) return cuts 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 file --------------------------------------------------------------- def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None, proof_fraction=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///.png (app/printtiles.py). A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`. 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']) pieces = sorted((Piece(placement, sources[placement['source_index']]) for placement in production['placements']), key=lambda piece: piece.y) # A proof sheet is a 15 cm window around the finest stroke; a normal # file is cut into parts (app/proof.py, item 0.1). cuts = (proof_cut(production['height_cm'], limit_cm, proof_fraction) if limit_cm else part_cuts(production, part_cm)) 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 '')) with open(path, 'wb') as out: manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), 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)], '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 write_part(out, pieces, top, bottom, width, footer=None, tiles=None): """Rows [top, bottom) of the film, 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 height = bottom - top + (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) 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)) writer.band(band) if pyramid: pyramid.band(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] if foot: writer.band(foot) if pyramid: pyramid.band(foot) writer.close() return pyramid.close() if pyramid else None