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:
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):
|
||||
|
||||
Reference in New Issue
Block a user