feat: the print file is a 300 DPI PNG, in parts of up to 15 m (item 13)
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m55s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m27s
FlexiPRINT's Spot OK 1 makes the white from transparency and reads it reliably only from a PNG (Dropstar's third round, item 13): each order item is now DTF-N-item-I.png, 300 DPI, RGBA on a transparent background, with its footer; a film over 15 m leaves as DTF-N-item-I-pK.png parts, each with "Parte K/N" in its footer, cut between pieces of loose art when it can be. app/printpng.py never holds a whole sheet: the film is composed and written in bands. Pillow encodes each band (it picks the PNG filters) and one zlib stream takes them; a long PNG sheet is read band by band by wrapping its compressed rows as small PNGs; a PDF page is drawn band by band at 300 DPI by PDFium (pypdfium2, a self-contained wheel); loose art is turned and scaled once. A 57 x 220 cm sheet peaks at 191 MB, a 15 m film at 279 MB. The parts of an item are dtf_local.print_parts (print_files.upload_id stays the first); the board, the final approval, the folders and the cleanup see every part, and the Kanban approves and downloads them all. A large PNG or PDF is now generated like any other; only other large formats go to hand preparation, and the original no longer stands in as the print file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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']
|
||||
|
||||
|
||||
|
||||
131
app/printjobs.py
131
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):
|
||||
|
||||
499
app/printpng.py
Normal file
499
app/printpng.py
Normal file
@@ -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()
|
||||
@@ -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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user