feat: the proof samples the file's colours too, up to 30 cm (Marcus, 2026-11-26)
Some checks failed
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Failing after 8m7s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Has been skipped

The proof keeps its 15 cm window on the finest stroke and adds 5 cm samples of
the colours that window lacks (12 hues, grey, white, black), 1 cm of clear film
between them, up to 30 cm. The colours are read from the small picture the
Site sends of each file, so a long film is scanned in a moment; without
pictures (a proof cut from a prepared final) it stays the stroke window. #100's
proof caught only its white art.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-26 12:05:45 -03:00
parent 4c6e2aac4a
commit 6d8dbf24ff
3 changed files with 254 additions and 52 deletions

View File

@@ -211,6 +211,12 @@ def render_one(storage):
job['proof_fallback'] = True
elif needs_designer(job['snapshot']):
job['wait_for_treatment'] = True
# The small pictures the Site sent of each file: where a proof finds
# the colours to sample (app/printpng.py film_scan).
if job['snapshot'].get('proof_of') and not job.get('proof_fallback'):
job['pictures'] = {str(r['upload_id']): bytes(r['data']) for r in c.execute(
'SELECT upload_id,data FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
(source_ids,)).fetchall()}
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
(source_ids,)).fetchall()
@@ -344,6 +350,15 @@ def footer(job, item):
return ' · '.join(fields)
def pictures_by_source(item, pictures):
"""The small pictures by source index, as the proof's scan reads them."""
if not pictures:
return None
sources = item['production']['sources']
found = {i: pictures[str(s['upload_id'])] for i, s in enumerate(sources) if str(s['upload_id']) in pictures}
return found or None
def produce(storage, job, item, uploads):
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
name)], evidence); the caller removes the folder."""
@@ -389,7 +404,8 @@ def produce(storage, job, item, uploads):
else file_prefix(job['number'], job['item_index']))
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
limit_cm=PROOF_SHEET_CM if proof_of else None,
proof_fraction=item.get('proof_y_fraction') if proof_of else None)
proof_fraction=item.get('proof_y_fraction') if proof_of else None,
pictures=pictures_by_source(item, job.get('pictures')))
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise

View File

@@ -449,16 +449,136 @@ def footer_band(text, width):
return band
# ---- The proof's samples ----------------------------------------------------
#
# Marcus, 2026-11-26: a proof of the finest stroke alone missed the colours
# (#100's caught only white art). The proof keeps its window on the finest
# stroke and adds short samples of the colours that window lacks, up to
# PROOF_MAX_CM in all, each apart by PROOF_GAP_CM of clear film.
PROOF_MAX_CM = Decimal('30')
PROOF_SAMPLE_CM = Decimal('5')
PROOF_GAP_CM = Decimal('1')
# Colour groups: 12 hues, then grey, white and black; 15 is no ink.
GREY, WHITE, BLACK, CLEAR = 12, 13, 14, 15
# A colour counts when it is this share of the film's ink, and is in a stretch
# when it is this share of the stretch's ink.
COLOUR_SHARE, PRESENT_SHARE = 0.02, 0.03
def colour_counts(band):
"""The band's ink by colour group, read on a copy an eighth the size."""
small = band.reduce(8) if min(band.size) >= 8 else band
alpha = small.getchannel('A')
hue, sat, val = small.convert('RGB').convert('HSV').split()
groups = hue.point(lambda h: h * 12 // 256)
achromatic = sat.point(lambda s: 255 if s < 46 else 0)
groups.paste(GREY, mask=achromatic)
groups.paste(WHITE, mask=Image.composite(val.point(lambda v: 255 if v > 217 else 0),
Image.new('L', small.size), achromatic))
groups.paste(BLACK, mask=val.point(lambda v: 255 if v < 64 else 0))
groups.paste(CLEAR, mask=alpha.point(lambda a: 255 if a < 128 else 0))
return groups.histogram()[:CLEAR]
def present(counts):
ink = sum(counts)
return {k for k, n in enumerate(counts) if ink and n >= PRESENT_SHARE * ink}
SCAN_PX_CM = 4
def film_scan(production, pictures):
"""The film's colours a centimetre at a time, [(top_cm, bottom_cm,
counts)], drawn from each file's small picture (the one the Site sends
for the Kanban, at most 480 x 720 px), so a 100 m film is read in a
moment. `pictures` maps a source index to its image bytes; a file
without one leaves its place empty."""
k = SCAN_PX_CM
film = Image.new('RGBA', (max(1, round(float(production['film_width_cm']) * k)),
max(1, round(float(production['height_cm']) * k))))
images = {}
for index, data in pictures.items():
try:
image = rgba(ImageOps.exif_transpose(Image.open(io.BytesIO(data))))
except Exception:
continue
spec = production['sources'][index]
top, bottom = (float(spec.get('trim_top_cm') or 0), float(spec.get('trim_bottom_cm') or 0))
if top or bottom:
# The picture is of the whole file: the Site cut the empty strips.
full = float(spec['length_cm']) + top + bottom
image = image.crop((0, round(image.height * top / full), image.width,
round(image.height * (full - bottom) / full)))
images[index] = image
for placement in production['placements']:
image = images.get(placement['source_index'])
if image is None:
continue
w = max(1, round(float(placement['width_cm']) * k))
h = max(1, round(float(placement['length_cm']) * k))
if placement['mirrored']:
image = ImageOps.mirror(image)
if placement['rotation_degrees'] % 360:
image = image.rotate(-placement['rotation_degrees'], expand=True)
film.alpha_composite(image.resize((w, h), Image.BOX),
(round(float(placement['x_cm']) * k), round(float(placement['y_cm']) * k)))
return [(Decimal(y) / k, Decimal(min(film.height, y + k)) / k, colour_counts(film.crop((0, y, film.width, y + k))))
for y in range(0, film.height, k)]
def proof_windows(height_cm, limit_cm, fraction, scan):
"""The proof's stretches of film, [(top, bottom)] in cm, from the top: the
finest stroke's window, then a PROOF_SAMPLE_CM sample for each colour
still missing, the most missing first. `scan` is [(top_cm, bottom_cm,
counts)] over the film."""
first = proof_cut(height_cm, limit_cm, fraction)
windows = [tuple(first)]
height = Decimal(str(height_cm))
total = sum((b - a for a, b in windows), Decimal(0))
ink = [sum(c[k] for _, _, c in scan) for k in range(CLEAR)]
wanted = {k for k, n in enumerate(ink) if sum(ink) and n >= COLOUR_SHARE * sum(ink)}
def inside(a, b):
# Only the centimetres wholly in the stretch: one on its edge may hold
# a colour the proof does not show.
return [c for top, bottom, c in scan if top >= a and bottom <= b]
covered = set().union(*(present(c) for a, b in windows for c in inside(a, b)))
while total + PROOF_GAP_CM + PROOF_SAMPLE_CM <= PROOF_MAX_CM and wanted - covered:
best = None
for top, bottom, counts in scan:
gain = (wanted - covered) & present(counts)
if not gain:
continue
centre = (top + bottom) / 2
a = min(height - PROOF_SAMPLE_CM, max(Decimal(0), centre - PROOF_SAMPLE_CM / 2)).quantize(Decimal('0.1'))
b = a + PROOF_SAMPLE_CM
if any(a < wb + PROOF_GAP_CM and b > wa - PROOF_GAP_CM for wa, wb in windows):
continue
score = (len(gain), sum(counts[k] for k in gain))
if best is None or score > best[0]:
best = (score, a, b)
if best is None:
break
_, a, b = best
windows.append((a, b))
total += PROOF_GAP_CM + (b - a)
covered |= set().union(*(present(c) for c in inside(a, b)))
return sorted(windows)
# ---- The file ---------------------------------------------------------------
def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False, limit_cm=None,
proof_fraction=None):
proof_fraction=None, pictures=None):
"""Write the PNG part(s) of one approved order item into `out_dir`.
`files` maps each source index to (local path, original name). With
`tiles`, each part's pieces for the Kanban's viewer go in
out_dir/tiles/<part name>/<level>/<index>.png (app/printtiles.py).
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`.
A proof (`limit_cm`) is a free 15 cm window around `proof_fraction`,
and samples of the colours it lacks, found in `pictures` (film_scan).
Returns the parts, [(path, name)], and the evidence the Kanban shows.
"""
production = item['production']
@@ -471,20 +591,29 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
vector = {index for index, source in enumerate(sources) if source.pdf}
lowest = check_layout(item, [source.size for source in sources], vector, proof=bool(limit_cm))
width = px(production['film_width_cm'])
windows = None
if limit_cm:
# A proof: the finest stroke's window and samples of the other
# colours, stacked in one sheet; a normal file is cut into parts.
windows = [tuple(proof_cut(production['height_cm'], limit_cm, proof_fraction))]
if pictures and Decimal(str(production['height_cm'])) > Decimal(str(limit_cm)):
windows = proof_windows(production['height_cm'], limit_cm, proof_fraction,
film_scan(production, pictures))
cuts = [windows[0][0], windows[-1][1]]
else:
cuts = part_cuts(production, part_cm)
pieces = sorted((Piece(placement, sources[placement['source_index']])
for placement in production['placements']), key=lambda piece: piece.y)
# A proof sheet is a 15 cm window around the finest stroke; a normal
# file is cut into parts (app/proof.py, item 0.1).
cuts = (proof_cut(production['height_cm'], limit_cm, proof_fraction) if limit_cm
else part_cuts(production, part_cm))
count = len(cuts) - 1
parts, manifests = [], []
for number in range(count):
name = f'{prefix}.png' if count == 1 else f'{prefix}-p{number + 1}.png'
path = os.path.join(out_dir, name)
line = footer and (footer + (f' · Parte {number + 1}/{count}' if count > 1 else ''))
ranges = ([(px(a), px(b)) for a, b in windows] if windows
else [(px(cuts[number]), px(cuts[number + 1]))])
with open(path, 'wb') as out:
manifests.append(write_part(out, pieces, px(cuts[number]), px(cuts[number + 1]), width, line,
manifests.append(write_part(out, pieces, ranges, width, line,
tiles=os.path.join(out_dir, 'tiles', name) if tiles else None))
parts.append((path, name))
finally:
@@ -497,6 +626,8 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
'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)],
**({'proof_windows': [[f'{Decimal(a).normalize():f}', f'{Decimal(b).normalize():f}']
for a, b in windows]} if windows else {}),
'footer': footer,
'billed_metres': str(item['billed_metres']),
'placements': len(production['placements']),
@@ -505,20 +636,9 @@ def render(item, files, out_dir, prefix, footer=None, part_cm=None, tiles=False,
'min_dpi': round(lowest) if lowest else None}
def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
"""Rows [top, bottom) of the film, then the footer, as one PNG; with
`tiles`, a folder, also its pieces for the viewer. Returns their manifest."""
foot = footer_band(footer, width) if footer else None
height = bottom - top + (foot.height if foot else 0)
writer = PngWriter(out, width, height)
pyramid = None
if tiles:
def emit(level, index, data):
folder = os.path.join(tiles, str(level))
os.makedirs(folder, exist_ok=True)
with open(os.path.join(folder, f'{index}.png'), 'wb') as strip:
strip.write(data)
pyramid = Pyramid(width, height, emit)
def film_bands(pieces, top, bottom, width):
"""The film's rows [top, bottom) composed, BAND_ROWS at a time: (band top,
RGBA image). Pieces are read forward only, so ranges go down the film."""
cache = {}
for band_top in range(top, bottom, BAND_ROWS):
band_bottom = min(bottom, band_top + BAND_ROWS)
@@ -534,9 +654,7 @@ def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
if left or piece.x + rows.width > width:
rows = rows.crop((left, 0, min(rows.width, width - piece.x), rows.height))
band.alpha_composite(rows, (max(0, piece.x), a - band_top))
writer.band(band)
if pyramid:
pyramid.band(band)
yield band_top, 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:
@@ -544,9 +662,36 @@ def write_part(out, pieces, top, bottom, width, footer=None, tiles=None):
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)
def write_part(out, pieces, ranges, width, footer=None, tiles=None):
"""The film's rows in `ranges` [(top, bottom)], top to bottom and apart by
PROOF_GAP_CM of clear film when there are several (a proof's samples),
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
gap = px(PROOF_GAP_CM)
height = (sum(b - a for a, b in ranges) + gap * (len(ranges) - 1) + (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)
def put(band):
writer.band(band)
if pyramid:
pyramid.band(foot)
pyramid.band(band)
for i, (top, bottom) in enumerate(ranges):
if i:
put(Image.new('RGBA', (width, gap)))
for _, band in film_bands(pieces, top, bottom, width):
put(band)
if foot:
put(foot)
writer.close()
return pyramid.close() if pyramid else None

View File

@@ -1,4 +1,5 @@
"""A free proof is a 15 cm window around the measured fine stroke, not the top."""
"""A free proof is a 15 cm window around the measured fine stroke, not the top,
and samples of the colours that window lacks, up to 30 cm (Marcus, 2026-11-26)."""
import io
import tempfile
import unittest
@@ -28,38 +29,78 @@ def item(height_cm=30, fraction='0.75'):
}
RED, BLUE, GREEN = (220, 30, 60, 255), (30, 60, 220, 255), (40, 180, 70, 255)
def cm(value):
return round(value * PX_CM)
def picture(path):
"""The small picture the Site sends of a file: WebP within 480 x 720 px."""
with Image.open(path) as image:
image.thumbnail((480, 720))
out = io.BytesIO()
image.save(out, 'WEBP', quality=80)
return out.getvalue()
class ProofRenderTests(unittest.TestCase):
def _sheet(self, folder):
height = round(30 * PX_CM)
width = round(20 * PX_CM)
image = Image.new('RGBA', (width, height), (220, 30, 60, 255))
ImageDraw.Draw(image).rectangle((0, height // 2, width - 1, height - 1),
fill=(30, 60, 220, 255))
def _sheet(self, folder, bands, height_cm=30):
"""A 20 cm wide sheet painted in [(from_cm, colour)] bands."""
image = Image.new('RGBA', (cm(20), cm(height_cm)), bands[0][1])
draw = ImageDraw.Draw(image)
for start, colour in bands[1:]:
draw.rectangle((0, cm(start), cm(20) - 1, cm(height_cm) - 1), fill=colour)
path = Path(folder) / 'sheet.png'
image.save(path, 'PNG', dpi=(300, 300))
return str(path)
def test_the_window_follows_the_finest_stroke(self):
def proof(self, bands, height_cm=30, fraction='0.75'):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15, proof_fraction='0.75')
sheet = self._sheet(source, bands, height_cm)
parts, detail = render(item(height_cm, fraction), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15, proof_fraction=fraction, pictures={0: picture(sheet)})
self.assertEqual(len(parts), 1)
self.assertEqual(detail['parts'][0]['from_cm'], '15')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.width, round(20 * PX_CM))
self.assertLessEqual(abs(proof.height - round(15 * PX_CM)), 1)
# The bottom half is blue: the window covered 15 to 30 cm.
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (30, 60, 220, 255))
with Image.open(parts[0][0]) as image:
return image.convert('RGBA'), detail
def test_the_top_is_still_the_default_without_a_measure(self):
def test_the_window_follows_the_finest_stroke_and_samples_the_rest(self):
# The stroke is in the blue half: its 15 cm window, then a 5 cm red
# sample from above, 1 cm of clear film between them.
image, detail = self.proof([(0, RED), (15, BLUE)])
self.assertEqual(detail['proof_windows'], [['0', '5'], ['15', '30']])
self.assertEqual(image.width, cm(20))
self.assertLessEqual(abs(image.height - cm(21)), 2)
self.assertEqual(image.getpixel((image.width // 2, cm(2))), RED)
self.assertEqual(image.getpixel((image.width // 2, cm(5.5)))[3], 0)
self.assertEqual(image.getpixel((image.width // 2, cm(10))), BLUE)
def test_the_top_is_still_the_window_without_a_measure(self):
image, detail = self.proof([(0, RED), (15, BLUE)], fraction=None)
self.assertEqual(detail['proof_windows'][0], ['0', '15'])
self.assertEqual(image.getpixel((image.width // 2, cm(5))), RED)
self.assertEqual(image.getpixel((image.width // 2, cm(18))), BLUE)
def test_without_pictures_the_proof_is_the_stroke_window(self):
with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as out:
sheet = self._sheet(source)
parts, detail = render(item(fraction=None), {0: (sheet, 'sheet.png')}, out, 'proof',
limit_cm=15)
self.assertEqual(detail['parts'][0]['from_cm'], '0')
with Image.open(parts[0][0]) as proof:
self.assertEqual(proof.getpixel((proof.width // 2, round(5 * PX_CM))), (220, 30, 60, 255))
sheet = self._sheet(source, [(0, RED), (15, BLUE)])
_, detail = render(item(), {0: (sheet, 'sheet.png')}, out, 'proof', limit_cm=15, proof_fraction='0.75')
self.assertEqual(detail['proof_windows'], [['15', '30']])
def test_one_colour_keeps_the_15_cm_proof(self):
image, detail = self.proof([(0, BLUE)])
self.assertEqual(detail['proof_windows'], [['15', '30']])
self.assertLessEqual(abs(image.height - cm(15)), 1)
def test_every_colour_within_30_cm(self):
# Red, blue and green in a 100 cm sheet, the stroke in the blue.
image, detail = self.proof([(0, RED), (30, BLUE), (60, GREEN)], height_cm=100, fraction='0.45')
windows = [(float(a), float(b)) for a, b in detail['proof_windows']]
self.assertEqual(len(windows), 3)
self.assertLessEqual(sum(b - a for a, b in windows) + 1 * (len(windows) - 1), 30)
colours = {image.getpixel((image.width // 2, y)) for y in range(0, image.height, cm(1))}
self.assertTrue({RED, BLUE, GREEN} <= colours, colours)
if __name__ == '__main__':