"""The ready-sheet orders whose sheet was stretched to the film (Marcus, 2026-12-02). Until the real-size rule (output/revisao/contrato-folha-real.md) the Site stretched every ready-sheet image to the film's width. A PNG that records its own DPI (200 or more, the A1 threshold) tells its real width, so an order whose sheet was laid out wider than that was printed bigger. Run once from the API's console: python -m ops.stretched_sheets since 2026-10-16 python -m ops.stretched_sheets --desde 2026-11-01 Read only. For each paid order (tests and cancelled ones left out) it prints the order number, the sheet's real width, the width it was laid out at and the factor. A sheet whose file is already gone (30 days after upload) or that records no DPI cannot be measured, and is listed apart. """ import argparse from datetime import date from app import payments from app.core import db from app.grade_check import Files, TRUSTED_DPI, image_size, png_saved_dpi SHEET_MODES = ('file', 'premium', 'uvfile') TOLERANCE_CM = 0.1 def sheets(order): """(item number, source number, source) for each measured ready sheet.""" for i, item in enumerate((order['snapshot'] or {}).get('items') or [], 1): if item.get('mode') not in SHEET_MODES: continue for n, source in enumerate((item.get('production') or {}).get('sources') or [], 1): if source.get('kind') == 'sheet' and source.get('measurement') == 'file': yield i, n, source def main(argv=None, out=print, storage=None, connect=db.connect): parser = argparse.ArgumentParser(prog='python -m ops.stretched_sheets') parser.add_argument('--desde', type=date.fromisoformat, default=date(2026, 10, 16)) args = parser.parse_args(argv) if storage is None: from app.runtime import storage files = Files(storage) stretched, unknown = [], [] with connect() as c: orders = c.execute('''SELECT id, number, snapshot, payment, created_at FROM dtf_local.orders WHERE created_at >= %s AND cancelled_at IS NULL AND parent_id IS NULL ORDER BY number''', (args.desde,)).fetchall() for order in orders: if payments.is_test(order): continue for i, n, source in sheets(order): row = c.execute('SELECT name, object_key, purged_at FROM dtf_local.uploads WHERE id=%s', (source['upload_id'],)).fetchone() label = f"#{order['number']} item {i} folha {n}" if not row or not row['name'].lower().endswith('.png'): continue # a PDF was always laid out at its page's width if row['purged_at']: unknown.append(f"{label} ({row['name']}): arquivo já apagado") continue try: head = files.head(row) except Exception as exc: # noqa: BLE001 - one unreadable file must not stop the list unknown.append(f"{label} ({row['name']}): não foi possível ler ({type(exc).__name__})") continue dpi, size = png_saved_dpi(head), image_size(head) if not size or dpi is None or dpi < TRUSTED_DPI: unknown.append(f"{label} ({row['name']}): o arquivo não grava o DPI") continue real = size[0] / dpi * 2.54 placed = float(source['width_cm']) if abs(placed - real) > TOLERANCE_CM: stretched.append((order['number'], label, row['name'], real, placed, placed / real)) comma = lambda v, places: f'{v:.{places}f}'.replace('.', ',') out(f'Pedidos de folha pronta desde {args.desde:%d/%m/%Y} montados com outra largura: {len(stretched)}') for _, label, name, real, placed, factor in stretched: out(f'{label}: {name} · largura real {comma(real, 1)} cm · montada com {comma(placed, 1)} cm · ' f'fator {comma(factor, 2)}') if unknown: out(f'Sem como medir: {len(unknown)}') for line in unknown: out(line) return stretched, unknown if __name__ == '__main__': main()