diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 8cc5ef4..775261c 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -86,7 +86,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v + run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules -v - name: Runtime and retention regressions run: | diff --git a/app/api/operator.py b/app/api/operator.py index 850559e..f108046 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -184,7 +184,7 @@ FINAL_OK = """f.kind='final' AND f.active AND u.expires_at>now() AND u.purged_at # their art, nor one of their originals, nor a correction they sent. `f` is # the final in dtf_local.order_files, `o` its order. TREATED = """f.kind='final' - AND NOT EXISTS (SELECT 1 FROM dtf_local.print_files p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id) + AND NOT EXISTS (SELECT 1 FROM dtf_local.print_parts p WHERE p.order_id=f.order_id AND p.upload_id=f.upload_id) AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? f.upload_id::text) AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files k WHERE k.order_id=f.order_id AND k.upload_id=f.upload_id AND k.kind='correction')""" @@ -211,6 +211,12 @@ def with_print_files(c, orders): generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,u.name FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (ids,)).fetchall() + # A film over 15 m is several PNGs, in order (item 13). + parts = c.execute('''SELECT p.order_id,p.item_index,p.part,p.upload_id,u.name FROM dtf_local.print_parts p + JOIN dtf_local.uploads u ON u.id=p.upload_id WHERE p.order_id=ANY(%s) ORDER BY p.part''', (ids,)).fetchall() + for row in generated: + row['parts'] = [{'upload_id': part['upload_id'], 'name': part['name']} for part in parts + if part['order_id'] == row['order_id'] and part['item_index'] == row['item_index']] finals = c.execute(f'''SELECT f.order_id,f.item_index,f.upload_id FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.order_id=ANY(%s) AND {FINAL_OK}''', (ids,)).fetchall() # Expired ones too: once corrected, a generated file is no longer the artwork. @@ -590,8 +596,9 @@ def delete_order(uid: UUID, user=Depends(can('manage'))): # order's). The worker deletes them within a minute. originals = {str(u) for item in row['snapshot'].get('items') or [] for u in item.get('uploads') or []} produced = {str(r['upload_id']) for r in c.execute('''SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s - UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL''', - (uid, uid)).fetchall()} + UNION SELECT upload_id FROM dtf_local.print_files WHERE order_id=%s AND upload_id IS NOT NULL + UNION SELECT upload_id FROM dtf_local.print_parts WHERE order_id=%s''', + (uid, uid, uid)).fetchall()} candidates = produced - originals if test else produced | originals for table in ('movements', 'order_files', 'print_files'): c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (uid,)) @@ -613,12 +620,13 @@ def release_files(c, uploads): for upload in uploads: used = c.execute('''SELECT 1 FROM dtf_local.order_files WHERE upload_id=%s UNION ALL SELECT 1 FROM dtf_local.print_files WHERE upload_id=%s + UNION ALL SELECT 1 FROM dtf_local.print_parts WHERE upload_id=%s UNION ALL SELECT 1 FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i WHERE i->'uploads' ? %s UNION ALL SELECT 1 FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i WHERE q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.orders x WHERE x.quote_id=q.id) AND i->'uploads' ? %s - LIMIT 1''', (upload, upload, upload, upload)).fetchone() + LIMIT 1''', (upload,) * 5).fetchone() if not used: free.append(upload) if free: @@ -1360,17 +1368,19 @@ def print_ready(c, states, only=None, paid_after=None): WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.cancelled_at IS NULL AND {FINAL_OK} UNION ALL - SELECT o.id,o.state,o.number,p.item_index,p.upload_id,u.object_key,u.name, + SELECT o.id,o.state,o.number,p.item_index,pp.upload_id,u.object_key,u.name, COALESCE(o.queue_key, extract(epoch FROM o.created_at)) FROM dtf_local.orders o - JOIN dtf_local.print_files p ON p.order_id=o.id JOIN dtf_local.uploads u ON u.id=p.upload_id + JOIN dtf_local.print_files p ON p.order_id=o.id + JOIN dtf_local.print_parts pp ON pp.order_id=p.order_id AND pp.item_index=p.item_index + JOIN dtf_local.uploads u ON u.id=pp.upload_id WHERE o.state=ANY(%s) AND (%s::uuid[] IS NULL OR o.id=ANY(%s)) AND (%s::timestamptz IS NULL OR o.created_at>=%s) AND o.state IN ('rec','tra') AND o.cancelled_at IS NULL AND p.status='ready' AND u.expires_at>now() AND u.purged_at IS NULL AND u.scan_state='clean' AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='final' AND f.active AND f.item_index=p.item_index) AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=o.id AND f.kind='correction') - ORDER BY position,order_id,item_index''', + ORDER BY position,order_id,item_index,name''', (list(states), ids, ids, paid_after, paid_after, list(states), ids, ids, paid_after, paid_after)).fetchall() return rows diff --git a/app/artwork.py b/app/artwork.py index bbfd3c6..95b3eac 100644 --- a/app/artwork.py +++ b/app/artwork.py @@ -20,8 +20,9 @@ def generated_owner(c, order, ref, kind): from, and only while that item still has its original artwork: after a customer correction it reproduces a layout nobody wants printed. """ - generated = c.execute('''SELECT item_index FROM dtf_local.print_files - WHERE order_id=%s AND upload_id=%s AND status='ready' ''', (order['id'], ref.upload_id)).fetchone() + generated = c.execute('''SELECT p.item_index FROM dtf_local.print_parts p JOIN dtf_local.print_files f + ON f.order_id=p.order_id AND f.item_index=p.item_index + WHERE p.order_id=%s AND p.upload_id=%s AND f.status='ready' ''', (order['id'], ref.upload_id)).fetchone() if not generated: return None if kind != 'final' or generated['item_index'] != ref.item_index: @@ -29,7 +30,6 @@ def generated_owner(c, order, ref, kind): if c.execute("SELECT 1 FROM dtf_local.order_files WHERE order_id=%s AND kind='correction' LIMIT 1", (order['id'],)).fetchone(): raise HTTPException(409, 'O cliente enviou uma correção depois que este arquivo foi gerado. Use a correção ou envie outro arquivo.') - # A large sheet's print file is its original, owned by the customer. return c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (ref.upload_id,)).fetchone()['owner'] diff --git a/app/printjobs.py b/app/printjobs.py index dc516eb..49e0cd5 100644 --- a/app/printjobs.py +++ b/app/printjobs.py @@ -5,19 +5,20 @@ claim, and renders outside any transaction, so a long render never holds a row lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to belong to a worker that died and is taken again. -The result is an ordinary upload row owned by an identity derived from the -order, already marked clean: its only inputs are artwork that passed the -malware scan, and the bytes are written here. The operator still decides -whether it becomes the final file; generation never approves anything. +The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a +film over 15 m: ordinary upload rows owned by an identity derived from the +order, already marked clean, since their only inputs are artwork that passed +the malware scan and the bytes are written here. dtf_local.print_parts lists +them in order. The operator still decides whether they become the final +file; generation never approves anything. -Sheets of several GB are the normal order, and decoding one would take more -memory than the worker has. A source above LARGE_SOURCE_BYTES is never -opened: a finished sheet placed whole on the film is already its own print -file, so the original becomes the print file; any other layout is prepared -by hand from the original. +Sheets of several GB are the normal order: a PNG or a PDF is read band by +band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES +is prepared by hand from the original. """ import logging import os +import shutil import tempfile import time from datetime import timedelta @@ -29,16 +30,18 @@ from psycopg.types.json import Jsonb from .core.auth import audit from .core.db import connect -from .printfile import Unsupported, render +from .printfile import Unsupported +from .printpng import render from .tiny import purchase_order LOCAL = ZoneInfo('America/Sao_Paulo') -CLAIM_TIMEOUT = timedelta(minutes=15) +# A 15 m part takes minutes to write; a long film, several parts. +CLAIM_TIMEOUT = timedelta(minutes=60) MAX_ATTEMPTS = 3 LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024))) -# Formats the operator can import as they are. -PRINTABLE_ORIGINAL = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.pdf') +# Read band by band, whatever their size. +STREAMED = ('.png', '.pdf') def generated_identity(order_id): @@ -81,18 +84,10 @@ def render_one(storage): expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)', ([UUID(u) for u in item['uploads']],)).fetchone()['e'] by_id = {str(row['id']): row for row in uploads} - if any(row['size'] > LARGE_SOURCE_BYTES for row in uploads): - original = whole_sheet(item, by_id) - if original: - with connect() as c: - c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s, - finished_at=now(), claimed_at=NULL WHERE id=%s''', - (original['id'], Jsonb({'source': 'original', 'name': original['name']}), job['id'])) - audit('print_file_original', order=str(job['order_id']), item=job['item_index']) - else: - finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB: ' - 'monte a folha a partir do original'}) - audit('print_file_manual', order=str(job['order_id']), item=job['item_index']) + if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads): + finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: ' + 'monte a folha a partir do original'}) + audit('print_file_manual', order=str(job['order_id']), item=job['item_index']) return True try: result = produce(storage, job, item, by_id) @@ -105,43 +100,35 @@ def render_one(storage): final = job['attempts'] + 1 >= MAX_ATTEMPTS finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__}) return True - path, name, size, detail = result + scratch, parts, detail = result + stored = [] try: - uid = uuid4() - key = f'originals/{uid}' - storage.store(key, path, 'application/pdf') + for path, name in parts: + uid = uuid4() + key = f'originals/{uid}' + storage.store(key, path, 'image/png') + stored.append((uid, name, os.path.getsize(path), key)) finally: - os.unlink(path) + shutil.rmtree(scratch, ignore_errors=True) + for part, (uid, _, size, _) in zip(detail['parts'], stored): + part.update(upload_id=str(uid), size=size) with connect() as c: - c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete, - expires_at,scan_state,scan_reason,scanned_at) - VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''', - (uid, generated_identity(job['order_id']), name, size, key, expiry)) + for uid, name, size, key in stored: + c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete, + expires_at,scan_state,scan_reason,scanned_at) + VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''', + (uid, generated_identity(job['order_id']), name, size, key, expiry)) c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s, - finished_at=now() WHERE id=%s''', (uid, Jsonb(detail), job['id'])) - audit('print_file_ready', order=str(job['order_id']), item=job['item_index']) + finished_at=now() WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id'])) + c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s', + (job['order_id'], job['item_index'])) + for number, (uid, _, _, _) in enumerate(stored, 1): + c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)', + (job['order_id'], job['item_index'], number, uid)) + audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored)) return True -def whole_sheet(item, uploads): - """The original, when the item is one finished sheet placed whole, once, - unrotated and unmirrored, across the film: then it is the print file.""" - spec = item.get('production') or {} - sources, placements = spec.get('sources') or [], spec.get('placements') or [] - if len(item['uploads']) != 1 or len(sources) != 1 or len(placements) != 1: - return None - source, place = sources[0], placements[0] - row = uploads.get(item['uploads'][0]) - if (not row or row['scan_state'] != 'clean' or row['purged_at'] or row['expired'] - or source.get('kind') != 'sheet' or int(source.get('copies', 1)) != 1 - or not row['name'].lower().endswith(PRINTABLE_ORIGINAL)): - return None - if (float(place['x_cm']) != 0 or float(place['y_cm']) != 0 or int(place['rotation_degrees']) != 0 - or place['mirrored'] or abs(float(source['width_cm']) - float(spec['film_width_cm'])) > 0.5): - return None - return row - - def file_prefix(number, item_index): """How an order's files are named: DTF-23-item-1, the code the Kanban copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23).""" @@ -166,30 +153,28 @@ def footer(job, item): def produce(storage, job, item, uploads): - """Fetch the item's artwork and render it. Returns (pdf path, name, size, evidence).""" + """Fetch the item's artwork and render it. Returns (folder, [(png path, + name)], evidence); the caller removes the folder.""" for upload_id in item['uploads']: row = uploads.get(upload_id) if not row or row['scan_state'] != 'clean': raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus') if row['purged_at'] or row['expired']: raise Unsupported('um arquivo original passou do prazo de guarda') - number = job['number'] - name = f'{file_prefix(number, job["item_index"])}.pdf' - with tempfile.TemporaryDirectory(prefix='print-') as scratch: - files = {} - for index, upload_id in enumerate(item['uploads']): - local = os.path.join(scratch, f'source-{index}') - storage.fetch(uploads[upload_id]['object_key'], local) - files[index] = (local, uploads[upload_id]['name']) - handle, output = tempfile.mkstemp(prefix='print-', suffix='.pdf') - try: - with os.fdopen(handle, 'wb') as out: - detail = render(item, files, out, f'Pedido {number} - item {job["item_index"] + 1}', - footer=footer(job, item)) - except BaseException: - os.unlink(output) - raise - return output, name, os.path.getsize(output), detail + output = tempfile.mkdtemp(prefix='print-') + try: + with tempfile.TemporaryDirectory(prefix='print-') as scratch: + files = {} + for index, upload_id in enumerate(item['uploads']): + local = os.path.join(scratch, f'source-{index}') + storage.fetch(uploads[upload_id]['object_key'], local) + files[index] = (local, uploads[upload_id]['name']) + parts, detail = render(item, files, output, file_prefix(job['number'], job['item_index']), + footer=footer(job, item)) + except BaseException: + shutil.rmtree(output, ignore_errors=True) + raise + return output, parts, detail def finish(job, status, detail): diff --git a/app/printpng.py b/app/printpng.py new file mode 100644 index 0000000..6bd757d --- /dev/null +++ b/app/printpng.py @@ -0,0 +1,499 @@ +"""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) + +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 + 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 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) + 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 + per_row = sh / 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, want_bottom = max(0, math.floor(a * per_row) - margin), min(sh, math.ceil(b * per_row) + 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 - self.buffer_top, sw, b - self.buffer_top)) + box = (0, a * per_row - self.buffer_top, sw, b * per_row - 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 _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): + """Write the PNG part(s) of one approved order item into `out_dir`. + + `files` maps each source index to (local path, original name). 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: + vector = {index for index, source in enumerate(sources) if source.pdf} + lowest = check_layout(item, [source.size for source in sources], vector) + width = px(production['film_width_cm']) + pieces = sorted((Piece(placement, sources[placement['source_index']]) + for placement in production['placements']), key=lambda piece: piece.y) + cuts = part_cuts(production, part_cm) + count = len(cuts) - 1 + parts = [] + 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: + write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line) + 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])} + 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): + """Rows [top, bottom) of the film, then the footer, as one PNG.""" + foot = footer_band(footer, width) if footer else None + writer = PngWriter(out, width, bottom - top + (foot.height if foot else 0)) + 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) + # 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) + writer.close() diff --git a/app/schema.sql b/app/schema.sql index 3d46210..0192e1b 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -203,6 +203,19 @@ CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_event CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at) WHERE status IN ('pending','rendering'); +-- The generated files of each item (item 13, 2026-10-29): one PNG, or the parts +-- of a film over 15 m, in order. print_files.upload_id stays the first. +CREATE TABLE IF NOT EXISTS dtf_local.print_parts ( + order_id uuid NOT NULL, item_index integer NOT NULL, part integer NOT NULL CHECK(part >= 1), + upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE, + PRIMARY KEY(order_id,item_index,part), + FOREIGN KEY(order_id,item_index) REFERENCES dtf_local.print_files(order_id,item_index) ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS print_parts_upload ON dtf_local.print_parts(upload_id); +INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) + SELECT order_id,item_index,1,upload_id FROM dtf_local.print_files WHERE upload_id IS NOT NULL + ON CONFLICT DO NOTHING; + -- A movement that undid an earlier one (a mistaken move), shown as such. ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false; diff --git a/infra/requirements.lock b/infra/requirements.lock index 32c0421..1454208 100644 --- a/infra/requirements.lock +++ b/infra/requirements.lock @@ -579,6 +579,31 @@ pydantic-core==2.46.5 \ --hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \ --hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9 # via pydantic +pypdfium2==5.14.0 \ + --hash=sha256:09b99c8f0cb427eb17fec13c0862ed598bba34b4843df153f70fff806a2820bc \ + --hash=sha256:11f281613fa22313d9c7ab89947665e84eccf8ebe40e1198a84a88352305648d \ + --hash=sha256:149fd5c6397b8df8bf7911a93506eff0be874f877afe7ac936cf5d37d21a6a06 \ + --hash=sha256:1951f0aed469150b13c62eabd501a9839e608ab9983ca8579be9eb73213b72b6 \ + --hash=sha256:2de384df66ba55fcaab0775f30f28ec1090af3dfa60276a07821efc96d993118 \ + --hash=sha256:382de7fe20d32c42993a274d7b6c555a5623a97570dfc1d2f5e0a16fe0d5d482 \ + --hash=sha256:51d9e9b64ebc34effaf57f9b6d4511b3f66ad3744bd1690d2cc6700853173dcf \ + --hash=sha256:593f2c952ae3ffdca0efcbb3d9464fbccb876254386114ff900cabef21157c3f \ + --hash=sha256:605ab9d0d4c5e223599c9065b88d16b2c1f131c807c80dea8adbb16f1433e95b \ + --hash=sha256:790e2cac1641a65912b73bd7243f45195d36f1663c85a3e1a126a8f5867c82a3 \ + --hash=sha256:9f4d77db5232826dd03a63481f32164331b96c21fd68f0667b2e43dbae141a93 \ + --hash=sha256:9fd5cc94a389d50298e4d8cb79af6b9b8e0d785606e2a937725dc6e271c9c6e6 \ + --hash=sha256:b40a0913196a1483f0fdc22a53f8719c3aef87f1c4d8d9c38d2ad4e207500fdf \ + --hash=sha256:bed597b2cea3990164e43f9003f71db18959d0abd5d73adc9c176e7be2d84b98 \ + --hash=sha256:c5f009b3157f10e97dceb55963f5910eff92feb00587ba10a76f12b87ce1a4b6 \ + --hash=sha256:c73be14076bedebd9bcaf9b062579c95c668580043bccd29eb0db502101d5716 \ + --hash=sha256:d436ee9e024f981e68f5775f5a9d115f93ea14ee6c2c6efd35dd17d83edf4942 \ + --hash=sha256:dbfd6deff68cc46b134acd6be380d98d694a9f018fbb622c07229225c85db389 \ + --hash=sha256:e4e203ea9710fd00e5448edb6f1615dc8587035357f75f40b432dde0c33e8da1 \ + --hash=sha256:e70d87cb0577eab38f2106f9c9606b458930beef612a1b5f298772ed259f5ec0 \ + --hash=sha256:eb8aeca157808f323e39ea298cc6d6c8e080c192ea2efb1ca81daa0f0ff4d095 \ + --hash=sha256:f1b696e6901e16f114a2ec6332e5e3f8f5033a901614ead28499ab18ca6024f5 \ + --hash=sha256:f6f13bbcc5f4adabc2676e52f662c6cb375de86b314790b0ae08f3ab62eb116a + # via -r infra/requirements.txt python-dateutil==2.9.0.post0 \ --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \ --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427 diff --git a/infra/requirements.txt b/infra/requirements.txt index 296e5a7..8ffa3fd 100644 --- a/infra/requirements.txt +++ b/infra/requirements.txt @@ -6,3 +6,4 @@ boto3==1.38.23 httpx==0.28.1 pillow==13.0.0 pikepdf==10.13.0.post1 +pypdfium2==5.14.0 diff --git a/tests/print_file_test.py b/tests/print_file_test.py index 39c9bef..b67e8ef 100644 --- a/tests/print_file_test.py +++ b/tests/print_file_test.py @@ -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() diff --git a/tests/test_large_files.py b/tests/test_large_files.py index 721675f..6067a67 100644 --- a/tests/test_large_files.py +++ b/tests/test_large_files.py @@ -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): diff --git a/tests/test_printpng.py b/tests/test_printpng.py new file mode 100644 index 0000000..66212b6 --- /dev/null +++ b/tests/test_printpng.py @@ -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() diff --git a/web/kanban.js b/web/kanban.js index 8a97046..9fede7f 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -1428,7 +1428,8 @@ function contractionList(order){ function approveParts(order,main=true){ const ready=readyFinals(order), all=ready.every(Boolean), many=ready.length>1; const files=node('div',undefined,'files'); - if(all)ready.forEach((r,i)=>files.append(fileRow(r.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source],downloadFile(r.upload_id)))); + if(all)ready.forEach((r,i)=>r.files.forEach((f,k)=>files.append(fileRow(f.name,(many?'Item '+(i+1)+', ':'')+FINAL_TITLE[r.source]+ + (r.files.length>1?', parte '+(k+1)+' de '+r.files.length:''),downloadFile(f.upload_id))))); const text=all?'Baixe e confira. É este arquivo que vai para a impressão.':ready.some(Boolean) ?'Alguns itens já têm arquivo pronto; envie o arquivo preparado dos outros.' :'Nenhum arquivo pronto para aprovar como está: envie o arquivo preparado para a impressão.'; @@ -1593,20 +1594,25 @@ function pickupDialog(order){ const isPickup=order=>order.snapshot.freight?.service==='pickup'; // ---- Final files: the file each item is printed from, approved by an operator. const finalDone=order=>order.snapshot.items.every((_,index)=>(order.final_items||[]).includes(index)); -const FINAL_SOURCE={correction:'correção do cliente',generated:'PDF gerado',original:'original'}; -const FINAL_TITLE={correction:'Correção do cliente',generated:'PDF gerado pelo sistema',original:'Original do cliente'}; -// Per item, a file that can be approved as it is, or null: the customer's -// correction, or else the generated PDF (or the original that already is one). -// After a correction, a generated file reproduces artwork nobody wants printed. +const FINAL_SOURCE={correction:'correção do cliente',generated:'arquivo gerado',original:'original'}; +const FINAL_TITLE={correction:'Correção do cliente',generated:'Gerado pelo sistema',original:'Original do cliente'}; +// What the system generated for an item: one PNG, or the parts of a film +// over 15 m (item 13). An item generated before parts has just its file. +const generatedFiles=row=>row.parts?.length?row.parts:[{upload_id:row.upload_id,name:row.name}]; +// Per item, the files that can be approved as they are, or null: the +// customer's correction, or else what the system generated (or the original +// that already was one). After a correction, a generated file reproduces +// artwork nobody wants printed. function readyFinals(order){ const fixes=order.corrections||[]; return order.snapshot.items.map((item,index)=>{ const fix=fixes.find(f=>f.item_index===index); - if(fix)return fix.expired?null:{upload_id:fix.upload_id,name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'}; + if(fix)return fix.expired?null:{files:[{upload_id:fix.upload_id,name:fix.name}],name:fix.name,source:'correction',label:'Correção do cliente ('+fix.name+')'}; const made=fixes.length?null:(order.print_files||[]).find(r=>r.item_index===index&&r.status==='ready'); if(!made)return null; - const original=made.detail?.source==='original'; - return {upload_id:made.upload_id,name:made.name,source:original?'original':'generated',label:(original?'O original (':'PDF gerado (')+made.name+')'}; + const original=made.detail?.source==='original', files=generatedFiles(made); + const names=files.length>1?files.length+' partes, '+files[0].name+' a '+files[files.length-1].name:files[0].name; + return {files,name:files[0].name,source:original?'original':'generated',label:(original?'O original (':'Gerado pelo sistema (')+names+')'}; }); } async function approveReady(order,ready){ @@ -1614,7 +1620,8 @@ async function approveReady(order,ready){ if(!await ask('Aprovar o arquivo final?','Conferiu? É este arquivo que vai para a impressão: '+ ready.map((r,i)=>(many?'item '+(i+1)+', ':'')+r.label).join('; ')+'.','Aprovar arquivo final',{host:$('drawer')}))return; const note='Aprovado como está: '+[...new Set(ready.map(r=>FINAL_SOURCE[r.source]))].join(', '); - await api('/orders/'+order.id+'/final-files',{version:order.version,files:ready.map((r,i)=>({item_index:i,upload_id:r.upload_id})),note}); + await api('/orders/'+order.id+'/final-files',{version:order.version, + files:ready.flatMap((r,i)=>r.files.map(f=>({item_index:i,upload_id:f.upload_id}))),note}); await load();say(mayMove(order.state,'tra')?'Arquivo final aprovado. Agora é só mover para Arte conferida.':'Arquivo final aprovado. Falta mover para Arte conferida.'); } // The file the operator prepared, per item; a ready file comes ticked. @@ -1631,7 +1638,7 @@ function finalDialog(order,ready,{replace=false}={}){ if(file){ const use=node('input');use.checked=true;use.dataset.useGenerated=index;input.required=false;drop.hidden=true; use.onchange=()=>{drop.hidden=use.checked;input.required=!use.checked;}; - slot.append(checkbox('Usar: '+file.label,use));input.generated=()=>use.checked?file.upload_id:null; + slot.append(checkbox('Usar: '+file.label,use));input.generated=()=>use.checked?file.files.map(f=>f.upload_id):null; } slot.append(drop);fields.push(slot);return input; }); @@ -1644,7 +1651,7 @@ function finalDialog(order,ready,{replace=false}={}){ const refs=[]; for(const [index,input] of inputs.entries()){ const generated=input.generated?.(); - if(generated){refs.push({item_index:index,upload_id:generated});continue;} + if(generated){refs.push(...generated.map(upload_id=>({item_index:index,upload_id})));continue;} for(const file of input.files){ const uid=await dtfUpload(file,{api,startPath:'/orders/'+order.id+'/uploads',scope:'operator:'+order.id+':'+order.version,progress:text=>say(text)}); refs.push({item_index:index,upload_id:uid}); @@ -1760,7 +1767,7 @@ function orderFacts(order){ if(order.machine||board.machines?.length)grid.append(machineCard(order)); return grid; } -const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'PDF gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'}; +const PRINT_TEXT={pending:'Na fila para gerar',rendering:'Gerando arquivo…',ready:'Arquivo gerado',manual:'Preparar à mão',failed:'Falhou ao gerar'}; // A line on an item: what is fine (ok), to look at (warn) or wrong (bad). function itemNote(text,tone=''){ const line=node('div',undefined,'inote'+(tone?' '+tone:'')); @@ -1812,7 +1819,10 @@ function itemCard(order,item,index){ const links=node('div',undefined,'links'); const dl_=(text,uid)=>{const b=downloadButton(text,download(uid),'btn');return b;}; if(fix&&!fix.expired)links.append(dl_('Correção',fix.upload_id)); - else if(row?.status==='ready'&&row.detail?.source!=='original')links.append(dl_('PDF',row.upload_id)); + else if(row?.status==='ready'&&row.detail?.source!=='original'){ + const made=generatedFiles(row); + made.forEach((f,k)=>links.append(dl_(made.length>1?'Parte '+(k+1)+' de '+made.length:/\.pdf$/i.test(f.name)?'PDF':'PNG',f.upload_id))); + } item.uploads.forEach((uid,i)=>links.append(dl_(item.uploads.length>1?'Original '+(i+1):'Arquivo original',uid))); if(spec?.placements){const m=button('Manifesto',()=>manifest(spec,contractionRecord(item,order.contraction?.[index])),'btn');m.prepend(svgIcon(IC.file,'i m'));links.append(m);} if(may('produce')&&!fix&&['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed')){