"""Make the Kanban's artwork pictures for orders and quotes from before them. The customer's browser makes each picture while uploading; older uploads have none, so their cards show "sem prévia". Run once from the worker's console: python -m ops.backfill_thumbnails makes the missing pictures python -m ops.backfill_thumbnails --limite 20 at most 20 this run Only PNG, JPEG and WebP: a PDF, CDR, AI or PSD needs a renderer the server does not have, and keeps showing the layout drawing. Files are read from storage one at a time, and very large images are skipped, so the worker is never asked for more memory than a normal sheet takes. Safe to run again: it only looks at uploads that still have no picture. """ import argparse import io import os import sys import tempfile from app.core import db # The Site's own picture size (site-upload.js: miniatura(..., 480, 720)). BOX = (480, 720) # Decoding a PNG takes about 4 bytes a pixel: 100 million pixels is ~400 MB. MAX_PIXELS = 100_000_000 MAX_BYTES = 300 * 1024 * 1024 IMAGES = ('.png', '.jpg', '.jpeg', '.webp') def missing(c, limit): """Uploads an order or a live quote refers to, still readable, without a picture.""" return c.execute('''WITH used AS ( SELECT (jsonb_array_elements_text(i->'uploads'))::uuid AS id FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i UNION SELECT (jsonb_array_elements_text(i->'uploads'))::uuid FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i WHERE q.discarded_at IS NULL AND q.created_at > now() - interval '3 days') SELECT u.id, u.name, u.size, u.object_key FROM dtf_local.uploads u JOIN used ON used.id=u.id LEFT JOIN dtf_local.upload_thumbnails t ON t.upload_id=u.id WHERE t.upload_id IS NULL AND u.complete AND u.purged_at IS NULL AND u.expires_at>now() AND u.scan_state='clean' ORDER BY u.created_at DESC LIMIT %s''', (limit,)).fetchall() def picture(path): """A WebP no larger than BOX, or None when the image is too large to decode.""" from PIL import Image Image.MAX_IMAGE_PIXELS = None # the size is checked here, before decoding with Image.open(path) as image: width, height = image.size if width * height > MAX_PIXELS: return None image.draft('RGB', BOX) # JPEG decodes at a reduced size image.thumbnail(BOX) out = io.BytesIO() image.convert('RGBA' if 'A' in image.getbands() or image.mode == 'P' else 'RGB').save( out, 'WEBP', quality=80) return out.getvalue() def main(argv=None, out=print, storage=None, connect=db.connect): parser = argparse.ArgumentParser(prog='python -m ops.backfill_thumbnails') parser.add_argument('--limite', type=int, default=500) args = parser.parse_args(argv) if storage is None: from app.runtime import storage with connect() as c: rows = missing(c, args.limite) made = skipped = 0 for row in rows: if not row['name'].lower().endswith(IMAGES) or (row['size'] or 0) > MAX_BYTES: skipped += 1 continue handle, path = tempfile.mkstemp(prefix='thumb-') os.close(handle) try: storage.fetch(row['object_key'], path) data = picture(path) except Exception as exc: # one unreadable file must not stop the others out(f"{row['name']}: não deu para ler ({type(exc).__name__})") skipped += 1 continue finally: os.unlink(path) if data is None: skipped += 1 continue with connect() as c: c.execute('''INSERT INTO dtf_local.upload_thumbnails(upload_id,mime,data) VALUES(%s,'image/webp',%s) ON CONFLICT (upload_id) DO NOTHING''', (row['id'], data)) made += 1 out(f'{made} miniatura(s) criada(s); {skipped} arquivo(s) sem miniatura possível (PDF, CDR, muito grande).') return 0 if __name__ == '__main__': sys.exit(main())