"""The grade recomputed from the uploaded files. The Site grades the art in the customer's browser and sends the grade with the cart. The price no longer depends on it (one price per product, 2026-10-23), but the grade is shown with the order on the Kanban and in Tiny. A customer who edits the page could claim a better grade, so before a cart is approved at checkout the server reads the files it already has and works the grade out again, by the Site's own rules: - a finished sheet: its pixel width over the sheet width is its DPI, and the item's grade comes from the worst sheet (web/site-quality.js); - artworks: each one's DPI along the width it is printed at, rotation included; the item's grade is the average of the artworks' grades; - a PDF: the area-weighted DPI of the images drawn on its page, 300 when it is only vectors (web/site-pdf.js, dpiDasImagens and resumoDpi). Images are measured from their first bytes, never decoded. A PDF is opened only up to PDF_MAX_BYTES, the size the Site itself analyses. Its DPI is worked out when the scan finishes and stored on the upload row (pdf_checked), so checkout uses the stored number and opens the file only when it is absent. A grade that cannot be recomputed is None; the caller decides what that means. """ import math import os import struct import tempfile DPI_IDEAL = 200 DPI_REFUSE = 96 PDF_VECTOR_DPI = 300 # The Site analyses PDFs up to 150 MB (GRANDE_BYTES); above that it does not # grade them, so neither does this. PDF_MAX_BYTES = 150 * 1048576 HEAD_BYTES = 1048576 # How much of a PDF's drawing is walked for its DPI: images and forms drawn # (Do), however many paths a vector page has. A page whose forms draw other # forms, ten times each, eight deep, is 10^8 draws in a 2 KB file: it # held the scanner's one thread for hours and every upload behind it # (security review, 2026-11-27). Past either limit the DPI is unknown, as for # a format this cannot read, and the order is reviewed by a person. PDF_MAX_DRAWS = 5000 PDF_MAX_SECONDS = 10 # Rounding in the browser and here can differ by a point on the same file. TOLERANCE = 2 def js_round(value): """Math.round, which rounds halves up; Python's round() does not.""" return math.floor(value + 0.5) def grade_of(dpi): return max(6, min(100, js_round(dpi / DPI_IDEAL * 100))) def image_size(head): """(width, height) in pixels from a PNG, JPEG or WebP's first bytes.""" if head[:8] == b'\x89PNG\r\n\x1a\n' and head[12:16] == b'IHDR': return struct.unpack('>II', head[16:24]) if head[:2] == b'\xff\xd8': i = 2 while i + 9 < len(head): if head[i] != 0xFF: i += 1 continue marker = head[i + 1] if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7 or marker == 0xFF: i += 1 if marker == 0xFF else 2 continue length = struct.unpack('>H', head[i + 2:i + 4])[0] if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC): h, w = struct.unpack('>HH', head[i + 5:i + 9]) return w, h i += 2 + length return None if head[:4] == b'RIFF' and head[8:12] == b'WEBP': chunk = head[12:16] if chunk == b'VP8X': return (int.from_bytes(head[24:27], 'little') + 1, int.from_bytes(head[27:30], 'little') + 1) if chunk == b'VP8L' and head[20] == 0x2F: bits = int.from_bytes(head[21:25], 'little') return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1 if chunk == b'VP8 ' and head[23:26] == b'\x9d\x01\x2a': w, h = struct.unpack(' deadline: raise _TooMuch op = str(operator) if op == 'q': stack.append(ctm) elif op == 'Q': ctm = stack.pop() if stack else [1, 0, 0, 1, 0, 0] elif op == 'cm': ctm = _multiply(ctm, [float(v) for v in operands]) elif op == 'Do' and operands: steps[0] += 1 if steps[0] > PDF_MAX_DRAWS or time.monotonic() > deadline: raise _TooMuch xobject = xobjects.get(str(operands[0])) if xobject is None: continue subtype = xobject.get('/Subtype') if subtype == '/Image': width_pt = math.hypot(ctm[0], ctm[1]) if width_pt >= 1: found.append((int(xobject.get('/Width', 0)) / (width_pt * unit / 72), abs(ctm[0] * ctm[3] - ctm[1] * ctm[2]))) elif subtype == '/Form' and depth < 8: matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])] walk(xobject.get('/Resources', resources), instructions_of(xobject), _multiply(ctm, matrix), depth + 1) walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0) except _TooMuch: import logging logging.warning('PDF %s draws more than %s images and forms, or takes over %s s: its DPI is left unknown', os.path.basename(path), PDF_MAX_DRAWS, PDF_MAX_SECONDS) return None except Exception: return None found = [(dpi, area) for dpi, area in found if dpi > 0] if not found: return PDF_VECTOR_DPI total = sum(area for _, area in found) or 1 return js_round(sum(dpi * area for dpi, area in found) / total) def _pdf_dpi_child(result, path): result.put(pdf_dpi(path)) def bounded_pdf_dpi(path): """pdf_dpi in a process of its own, ended past PDF_MAX_SECONDS: the PDF library itself can be held by a file (a huge compressed stream), where pdf_dpi's own limits cannot reach. None when it did not finish.""" import multiprocessing from queue import Empty context = multiprocessing.get_context('spawn') result = context.Queue() process = context.Process(target=_pdf_dpi_child, args=(result, path)) process.start() try: process.join(PDF_MAX_SECONDS + 5) if process.is_alive(): process.kill() process.join() import logging logging.warning('PDF %s took over %s s to read: its DPI is left unknown', os.path.basename(path), PDF_MAX_SECONDS + 5) return None try: return result.get(timeout=5) except Empty: return None finally: result.close() result.join_thread() def stored_pdf_dpi(storage, row): """A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES or takes too long to read (bounded_pdf_dpi).""" if row['size'] > PDF_MAX_BYTES: return None with tempfile.NamedTemporaryFile(suffix='.pdf') as handle: storage.client.download_fileobj(storage.bucket, row['object_key'], handle) handle.flush() return bounded_pdf_dpi(handle.name) class Files: """The uploaded files, read from storage as little as needed.""" def __init__(self, storage): self.storage = storage # A PDF is read once per quote: source_dpi, resolution_issue and # mismatch all ask for the same files. self._heads = {} self._dpis = {} def head(self, row): key = row['object_key'] if key not in self._heads: self._heads[key] = self.storage.client.get_object( Bucket=self.storage.bucket, Key=key, Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read() return self._heads[key] def pdf_dpi(self, row): key = row['object_key'] if key not in self._dpis: if row.get('pdf_checked'): self._dpis[key] = row['pdf_dpi'] else: self._dpis[key] = stored_pdf_dpi(self.storage, row) return self._dpis[key] def source_dpi(files, row, source): """One source's DPI across the width it is printed at, or None.""" name = row['name'].lower() width_in = float(source['width_cm']) / 2.54 if name.endswith('.pdf'): return files.pdf_dpi(row) if source['kind'] == 'sheet' else None if not name.endswith(('.png', '.jpg', '.jpeg', '.webp')): return None size = image_size(files.head(row)) if not size or not all(size): return None across = size[1] if source['rotation_degrees'] in (90, 270) else size[0] return across / width_in def item_grade(files, item, rows): """The grade the Site gives this item, recomputed; None if it cannot be.""" sources = item['production']['sources'] dpis = [] for source in sources: row = rows.get(str(source['upload_id'])) dpi = source_dpi(files, row, source) if row else None if dpi is None: return None dpis.append(dpi) if all(source['kind'] == 'sheet' for source in sources): # A sheet's DPI is shown and compared as a whole number. return grade_of(min(js_round(d) for d in dpis)) return js_round(sum(grade_of(d) for d in dpis) / len(dpis)) def resolution_issue(files, items, rows): """Refuse sub-96 DPI and require recorded consent for measurable 96–199 DPI. Unknown formats remain for manual review; they cannot be treated as a measured zero DPI or silently called high-resolution artwork. """ for index, item in enumerate(items, 1): dpis = [] for source in item['production']['sources']: row = rows.get(str(source['upload_id'])) dpi = source_dpi(files, row, source) if row else None if dpi is None: dpis = [] break dpis.append(dpi) if not dpis: continue # The Site shows and compares the rounded DPI (web/site-quality.js, # site-pdf.js): decide on the same whole number, not the raw fraction. shown = js_round(min(dpis)) if shown < DPI_REFUSE: return f'Item {index}: resolução de {shown} DPI abaixo do mínimo de {DPI_REFUSE} DPI.' if shown < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']): return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.' return None def proportion_issue(files, items, rows): """Why a cart's layout cannot be priced, or None: a raster file laid out at proportions it does not have (a 5 m sheet sent as 10 cm, say). The print file refuses the same thing (app/printfile.py check_layout), but only after payment; here it is refused before. A PDF, or a file whose size the first bytes do not tell, is left to that later check.""" from .printfile import ASPECT_TOLERANCE for index, item in enumerate(items, 1): for number, source in enumerate(item['production']['sources'], 1): row = rows.get(str(source['upload_id'])) if not row or row['name'].lower().endswith('.pdf'): continue size = image_size(files.head(row)) if not size or not all(size): continue width_px, height_px = size if source.get('rotation_degrees') in (90, 270): width_px, height_px = height_px, width_px # A ready sheet's empty strips were cut from its length: the file # is the length plus both strips (app/core/models.py). length = (float(source['length_cm']) + float(source.get('trim_top_cm') or 0) + float(source.get('trim_bottom_cm') or 0)) drift = abs((width_px / height_px) / (float(source['width_cm']) / length) - 1) if drift > ASPECT_TOLERANCE: return (f'Item {index}: o arquivo {number} foi montado com {source["width_cm"]} × ' f'{source["length_cm"]} cm, que não são as proporções dele. Monte o pedido de novo.') return None # A ready sheet in the 57 cm textile products must be 57 cm wide where its real # width is known (Marcus, 2026-12-01: a pop-up on upload and refused, narrower # or wider). Known means a PNG whose pHYs records TRUSTED_DPI or more (the A1 # threshold, rodada 5) or a PDF page; anything else keeps the v0 rule (the # image stretched to the film). output/revisao/contrato-largura-folha.md; # the Site has the same numbers (web/site-config.js LARGURA_EXATA). EXACT_SHEET_WIDTH_CM = {'file': 57.0, 'premium': 57.0} SHEET_WIDTH_TOLERANCE_CM = 0.1 TRUSTED_DPI = 200 def png_saved_dpi(head): """The DPI a PNG records in its pHYs chunk, rounded as the Site rounds it (web/site-pdf.js dpiSalvoPng: Math.round(pixels per metre × 0.0254)), or None: not a PNG, no pHYs before the first IDAT, a unit that is not the metre, X and Y that differ, or a chunk cut off by the head's end.""" if head[:8] != b'\x89PNG\r\n\x1a\n': return None offset = 8 while offset + 8 <= len(head): length = struct.unpack('>I', head[offset:offset + 4])[0] kind = head[offset + 4:offset + 8] if kind in (b'IDAT', b'IEND'): return None end = offset + 8 + length if end + 4 > len(head): return None # chunk cut off by the head's end if kind == b'pHYs': if length < 9: return None ppm_x, ppm_y, unit = struct.unpack('>IIB', head[offset + 8:offset + 17]) if unit == 1 and ppm_x == ppm_y > 0: return js_round(ppm_x * 0.0254) return None offset = end + 4 return None def sheet_width_issue(files, items, rows): """Why a cart cannot be approved: a ready sheet of a 57 cm textile item (EXACT_SHEET_WIDTH_CM) whose real width is off by more than SHEET_WIDTH_TOLERANCE_CM, or None. A PNG's real width is its pixels ÷ its pHYs DPI × 2.54 when that DPI is TRUSTED_DPI or more; a PDF's is the source's width_cm (the page the Site measured). Anything else passes.""" for index, item in enumerate(items, 1): mode = item.get('mode') if mode not in EXACT_SHEET_WIDTH_CM: continue expected = EXACT_SHEET_WIDTH_CM[mode] expected_text = f'{expected:g}' for number, source in enumerate(item['production']['sources'], 1): if source.get('kind') != 'sheet': continue row = rows.get(str(source['upload_id'])) if not row: continue name = row['name'].lower() if name.endswith('.pdf'): cm = float(source['width_cm']) dpi = None elif name.endswith('.png'): dpi = png_saved_dpi(files.head(row)) if dpi is None or dpi < TRUSTED_DPI: continue size = image_size(files.head(row)) if not size or not all(size): continue cm = size[0] / dpi * 2.54 else: continue if abs(cm - expected) <= SHEET_WIDTH_TOLERANCE_CM: continue cm_text = f'{cm:.1f}'.replace('.', ',') if dpi is None: return (f'Item {index}: a folha {number} tem {cm_text} cm de largura. ' f'A folha montada precisa ter {expected_text} cm.') return (f'Item {index}: a folha {number} tem {cm_text} cm de largura ({dpi} DPI). ' f'A folha montada precisa ter {expected_text} cm.') return None def mismatch(files, items, rows): """Why a cart's grades cannot be approved at checkout, or None.""" for item in items: if item['grade'] == 0: continue # no grade claimed: nothing to verify verified = item_grade(files, item, rows) if verified is None: return 'Nota não conferida no servidor' if item['grade'] > verified + TOLERANCE: return f"Nota {item['grade']} maior que a do arquivo ({verified})" return None