feat: "Abrir e conferir", the print file full screen, in pieces (item 7)
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 4m28s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m17s

The card's "Abrir e conferir" opens the order's print file full screen
(Dropstar's third round, item 7): zoom up to 100% real (one file pixel, one
screen pixel), the position in cm, the order's files one after the other
without closing, and the background behind the transparency light, dark or
checkered, remembered (Dropstar, 2026-10-30). Closed in Arte recebida, it asks
"Está OK?": the class of each item, prefilled with the measure, then
"Mover para Arte conferida" (the final approved, the class kept, the card
moved) or "Tratar a arte".

A 15 m film is loaded like a map: while the PNG is written, its strips of
512 rows go to storage at 100% and at each halving (app/printtiles.py,
originals/tiles/<upload>/), and the viewer (web/kanban-viewer.js) fetches
only those on screen. They go when their file expires. Storing a print file
that fails is now an attempt like a failed render, not a claim held for an
hour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-03 20:10:03 -03:00
parent e3a5ad6fa0
commit 8b7d9f0bdb
12 changed files with 483 additions and 11 deletions

View File

@@ -205,6 +205,8 @@ class ObjectStorage(Protocol):
def store(self, key: str, path: str, content_type: str): ...
def health(self): ...
def discard(self, key: str, upload_id: str, complete: bool): ...
def discard_prefix(self, prefix: str): ...
def view(self, key: str, content_type: str, expires: int = 3600) -> str: ...
class LocalS3Storage:
def __init__(self):
@@ -266,6 +268,25 @@ class LocalS3Storage:
'ResponseContentDisposition': "attachment; filename*=UTF-8''" + quote(name, safe=''),
'ResponseContentType': 'application/octet-stream'}, ExpiresIn=300)
def view(self, key, content_type, expires=3600):
"""A link to show an object in the page, not download it: the Kanban's
viewer reads a film's pieces for as long as it is open (item 7)."""
return self.public.generate_presigned_url('get_object', Params={
'Bucket': self.bucket, 'Key': key, 'ResponseContentType': content_type}, ExpiresIn=expires)
def discard_prefix(self, prefix):
"""Delete every object under `prefix`, such as a print file's pieces."""
token = None
while True:
page = self.client.list_objects_v2(Bucket=self.bucket, Prefix=prefix,
**({'ContinuationToken': token} if token else {}))
keys = [{'Key': item['Key']} for item in page.get('Contents', [])]
if keys:
self.client.delete_objects(Bucket=self.bucket, Delete={'Objects': keys, 'Quiet': True})
if not page.get('IsTruncated'):
return
token = page['NextContinuationToken']
def discard(self, key, upload_id, complete):
if not complete:
try:

View File

@@ -1399,6 +1399,47 @@ def print_ready(c, states, only=None, paid_after=None):
return rows
@router.get('/api/operator/orders/{uid}/view')
def view_files(uid: UUID, user=Depends(operator)):
"""What "Abrir e conferir" shows (item 7): each item's generated PNG, part
by part, with links to its pieces, then the customer's originals, which
have only their picture."""
with db.connect() as c:
order = c.execute('SELECT snapshot FROM dtf_local.orders WHERE id=%s', (uid,)).fetchone()
if not order:
raise HTTPException(404, 'Pedido não encontrado.')
made = c.execute('''SELECT item_index, detail FROM dtf_local.print_files WHERE order_id=%s AND status='ready'
ORDER BY item_index''', (uid,)).fetchall()
parts = c.execute('''SELECT 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=%s AND u.purged_at IS NULL
ORDER BY p.item_index, p.part''', (uid,)).fetchall()
pictured = {str(r['upload_id']) for r in c.execute(
'SELECT upload_id FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
([UUID(u) for item in order['snapshot']['items'] for u in item['uploads']],)).fetchall()}
items = order['snapshot']['items']
many = len(items) > 1
files = []
for row in made:
mine = [p for p in parts if p['item_index'] == row['item_index']]
details = {d.get('name'): d for d in row['detail'].get('parts') or []}
for part in mine:
tiles = (details.get(part['name']) or {}).get('tiles')
label = (f"Item {row['item_index'] + 1}" if many else 'Arquivo') + \
(f" · parte {part['part']}/{len(mine)}" if len(mine) > 1 else '')
files.append({'name': part['name'], 'label': label, 'item': row['item_index'],
'manifest': tiles and {**tiles, 'urls': [
[storage.view(f"originals/tiles/{part['upload_id']}/{k}/{i}.png", 'image/png')
for i in range(level['strips'])] for k, level in enumerate(tiles['levels'])]}})
for index, item in enumerate(items):
for n, upload in enumerate(item['uploads']):
files.append({'name': ('Original ' + str(n + 1)) if len(item['uploads']) > 1 else 'Original',
'label': (f'Item {index + 1} · ' if many else '') + 'original' +
(f' {n + 1}' if len(item['uploads']) > 1 else ''),
'item': index, 'manifest': None,
'picture': f'/api/operator/uploads/{upload}/thumbnail' if upload in pictured else None})
return {'files': files}
@router.get('/api/operator/orders/{uid}/folder-files')
def folder_files(uid: UUID, user=Depends(can('produce'))):
"""What each item's file is called in the order's stage folder, as the

View File

@@ -108,6 +108,12 @@ def render_one(storage):
key = f'originals/{uid}'
storage.store(key, path, 'image/png')
stored.append((uid, name, os.path.getsize(path), key))
store_tiles(storage, os.path.join(scratch, 'tiles', name), uid)
except Exception as exc:
# Storage failing is an attempt like any other, not a claim held for an hour.
logging.exception('Storing the print file failed')
finish(job, 'failed' if job['attempts'] + 1 >= MAX_ATTEMPTS else 'pending', {'error': type(exc).__name__})
return True
finally:
shutil.rmtree(scratch, ignore_errors=True)
for part, (uid, _, size, _) in zip(detail['parts'], stored):
@@ -129,6 +135,16 @@ def render_one(storage):
return True
def store_tiles(storage, folder, upload_id):
"""A part's pieces for the Kanban's viewer (item 7), beside the files the
storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
if not os.path.isdir(folder):
return
for level in sorted(os.listdir(folder)):
for strip in sorted(os.listdir(os.path.join(folder, level))):
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
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)."""
@@ -170,7 +186,7 @@ def produce(storage, job, item, uploads):
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))
footer=footer(job, item), tiles=True)
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise

View File

@@ -36,6 +36,7 @@ from PIL import Image, ImageDraw, ImageFont, ImageOps
from .core.models import PRODUCTION_VERSIONS
from .printfile import (FOOTER_CM, FOOTER_LOGO, FOOTER_LOGO_CM, MAX_DECODED_PIXELS, SUPPORTED_FORMATS,
Unsupported, check_layout)
from .printtiles import Pyramid
DPI = 300
PX_PER_CM = DPI / 2.54
@@ -424,11 +425,13 @@ def footer_band(text, width):
# ---- The file ---------------------------------------------------------------
def render(item, files, out_dir, prefix, footer=None, part_cm=None):
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False):
"""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.
`files` maps each source index to (local path, original name). With
`tiles`, each part's pieces for the Kanban's viewer go in
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
Returns the parts, [(path, name)], and the evidence the Kanban shows.
"""
production = item['production']
if production.get('version') not in PRODUCTION_VERSIONS:
@@ -442,13 +445,14 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None):
for placement in production['placements']), key=lambda piece: piece.y)
cuts = part_cuts(production, part_cm)
count = len(cuts) - 1
parts = []
parts, manifests = [], []
for number in range(count):
name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png'
path = os.path.join(out_dir, name)
line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else ''))
with open(path, 'wb') as out:
write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line)
manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line,
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
parts.append((path, name))
finally:
for source in sources:
@@ -457,7 +461,8 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None):
'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])}
'parts': [{'name': name, 'from_cm': str(cuts[i]), 'to_cm': str(cuts[i + 1]),
**({'tiles': manifests[i]} if manifests[i] else {})}
for i, (_, name) in enumerate(parts)],
'footer': footer,
'billed_metres': str(item['billed_metres']),
@@ -467,10 +472,20 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None):
'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."""
def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
"""Rows [top, bottom) of the film, then the footer, as one PNG; with
`tiles`, a folder, also its pieces for the viewer. Returns their manifest."""
foot = footer_band(footer, width) if footer else None
writer = PngWriter(out, width, bottom - top + (foot.height if foot else 0))
height = bottom - top + (foot.height if foot else 0)
writer = PngWriter(out, width, height)
pyramid = None
if tiles:
def emit(level, index, data):
folder = os.path.join(tiles, str(level))
os.makedirs(folder, exist_ok=True)
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
strip.write(data)
pyramid = Pyramid(width, height, emit)
cache = {}
for band_top in range(top, bottom, BAND_ROWS):
band_bottom = min(bottom, band_top + BAND_ROWS)
@@ -487,6 +502,8 @@ def write_part(out, pieces, top, bottom, width, footer=None):
rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height))
band.alpha_composite(rows, (max(0, piece.x), a - band_top))
writer.band(band)
if pyramid:
pyramid.band(band)
# A piece the film has passed is done with: its pixels can go.
for piece in pieces:
if piece.y + piece.h <= band_bottom:
@@ -496,4 +513,7 @@ def write_part(out, pieces, top, bottom, width, footer=None):
del cache[key]
if foot:
writer.band(foot)
if pyramid:
pyramid.band(foot)
writer.close()
return pyramid.close() if pyramid else None

102
app/printtiles.py Normal file
View File

@@ -0,0 +1,102 @@
"""The print file in pieces, for the Kanban's viewer (Dropstar's third round, item 7).
"Abrir e conferir" shows the PNG at up to 100% (one file pixel, one screen
pixel). A 57 cm x 15 m film is 160 million pixels per 2 m: loaded whole it
freezes the designer's computer, so the viewer loads it in pieces, like a map.
The pieces are strips of the film's whole width, STRIP_ROWS tall, at 100%
and at each halving down to a few strips for the whole film: level 0 is the
file itself, level k is 1/2^k of it. They are written while the PNG is, from
the same bands, so the file is never read back.
"""
import io
import math
from PIL import Image
STRIP_ROWS = 512
# Levels stop when the whole film fits in about one screen.
SMALLEST_ROWS = 1024
def levels_for(height):
"""How many levels a film of `height` px gets: halving until it is short."""
count = 1
while math.ceil(height / 2 ** (count - 1)) > SMALLEST_ROWS and count < 12:
count += 1
return count
class Pyramid:
"""Fed the film's bands from the top, it hands each finished strip, as a
PNG, to `emit(level, index, png_bytes)`."""
def __init__(self, width, height, emit):
self.width, self.height, self.emit = width, height, emit
self.levels = levels_for(height)
self.pending = [None] * self.levels # rows of each level not yet a strip
self.count = [0] * self.levels # strips written per level
# A level's odd last row waits for its pair.
self.odd = [None] * self.levels
def band(self, image):
self._feed(0, image)
def _feed(self, level, image):
if level >= self.levels:
return
rows = self.pending[level]
if rows is None:
rows = image
else:
joined = Image.new('RGBA', (image.width, rows.height + image.height))
joined.paste(rows, (0, 0))
joined.paste(image, (0, rows.height))
rows = joined
while rows.height >= STRIP_ROWS:
self._strip(level, rows.crop((0, 0, rows.width, STRIP_ROWS)))
rows = rows.crop((0, STRIP_ROWS, rows.width, rows.height)) if rows.height > STRIP_ROWS else None
if rows is None:
break
self.pending[level] = rows
# The next level down, from these rows, two by two.
self._halve(level, image)
def _halve(self, level, image):
if level + 1 >= self.levels:
return
if self.odd[level] is not None:
joined = Image.new('RGBA', (image.width, image.height + 1))
joined.paste(self.odd[level], (0, 0))
joined.paste(image, (0, 1))
image, self.odd[level] = joined, None
if image.height % 2:
self.odd[level] = image.crop((0, image.height - 1, image.width, image.height))
image = image.crop((0, 0, image.width, image.height - 1))
if image.height:
small = image.resize((max(1, math.ceil(image.width / 2)), image.height // 2), Image.BOX)
self._feed(level + 1, small)
def _strip(self, level, image):
out = io.BytesIO()
image.save(out, 'PNG', compress_level=1)
self.emit(level, self.count[level], out.getvalue())
self.count[level] += 1
def close(self):
"""Flush what is left at each level, from the top level down."""
for level in range(self.levels):
if self.odd[level] is not None and level + 1 < self.levels:
last = self.odd[level]
self.odd[level] = None
self._feed(level + 1, last.resize((max(1, math.ceil(last.width / 2)), 1), Image.BOX))
if self.pending[level] is not None and self.pending[level].height:
self._strip(level, self.pending[level])
self.pending[level] = None
return self.manifest()
def manifest(self):
return {'width': self.width, 'height': self.height, 'strip_rows': STRIP_ROWS,
'levels': [{'scale': 1 / 2 ** k, 'width': math.ceil(self.width / 2 ** k),
'height': math.ceil(self.height / 2 ** k), 'strips': self.count[k]}
for k in range(self.levels)]}

View File

@@ -39,6 +39,9 @@ def cleanup():
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
for row in rows:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
# A generated PNG's pieces for the Kanban's viewer go with it (item 7).
if row['name'].lower().endswith('.png'):
storage.discard_prefix(f"originals/tiles/{row['id']}/")
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')