|
| 1 | +""" |
| 2 | +Cheap pre-check run *before* any (paid) Groq vision call: does this frame |
| 3 | +actually contain a sharp, framed trading card? |
| 4 | +
|
| 5 | +A phone camera in "cash register" mode streams many frames; without this gate |
| 6 | +an empty desk, a blurry pan or a finger would each cost a Groq request and |
| 7 | +trip 429s. Pure Pillow + stdlib — no numpy / OpenCV dependency. |
| 8 | +
|
| 9 | +Heuristics (all must pass): |
| 10 | +
|
| 11 | +* **detail** — luminance stddev. An empty/uniform surface is flat. |
| 12 | +* **focus** — edge-energy spread (variance-of-Laplacian proxy). A blurry |
| 13 | + or motion-smeared frame has little high-frequency content. |
| 14 | +* **framing** — the "busy" region (thresholded edges) must fill a large, |
| 15 | + roughly centered, card-proportioned part of the frame, i.e. an actual card |
| 16 | + presented to the lens rather than clutter in a corner. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import io |
| 22 | +import logging |
| 23 | +from dataclasses import dataclass |
| 24 | + |
| 25 | +from PIL import Image, ImageFilter, ImageOps, ImageStat |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | +#: Long edge the frame is downscaled to before analysis (speed). |
| 30 | +_ANALYZE_EDGE = 256 |
| 31 | +#: Edge-map binarisation threshold (0–255) for the "busy region" mask. |
| 32 | +_EDGE_BIN_THRESHOLD = 38 |
| 33 | + |
| 34 | +# --- Acceptance thresholds (strict: better to skip a frame than to spam Groq; |
| 35 | +# a real card held in frame produces several qualifying frames anyway). |
| 36 | +_MIN_DETAIL_STDDEV = 17.0 |
| 37 | +_MIN_FOCUS = 9.0 |
| 38 | +_MIN_FILL = 0.42 |
| 39 | +_CENTER_LO = 0.22 |
| 40 | +_CENTER_HI = 0.78 |
| 41 | +_CARD_AR_MIN = 0.45 |
| 42 | +_CARD_AR_MAX = 2.20 |
| 43 | + |
| 44 | + |
| 45 | +@dataclass(frozen=True) |
| 46 | +class CardGateResult: |
| 47 | + """Outcome of :func:`assess_card_image`.""" |
| 48 | + |
| 49 | + is_card: bool |
| 50 | + #: ``ok`` | ``unreadable`` | ``too_small`` | ``empty`` | ``blurry`` | ``no_card`` |
| 51 | + reason: str |
| 52 | + detail: float |
| 53 | + focus: float |
| 54 | + fill: float |
| 55 | + |
| 56 | + |
| 57 | +def _bbox_metrics(edges: Image.Image, w: int, h: int) -> tuple[float, bool, bool]: |
| 58 | + """Return ``(fill_ratio, centered, aspect_ok)`` for the thresholded edge map.""" |
| 59 | + lut = [0 if i <= _EDGE_BIN_THRESHOLD else 255 for i in range(256)] |
| 60 | + box = edges.point(lut).getbbox() |
| 61 | + if not box: |
| 62 | + return 0.0, False, False |
| 63 | + bx0, by0, bx1, by1 = box |
| 64 | + bw = max(1, bx1 - bx0) |
| 65 | + bh = max(1, by1 - by0) |
| 66 | + fill = (bw * bh) / float(w * h) |
| 67 | + cx = (bx0 + bx1) / 2.0 / w |
| 68 | + cy = (by0 + by1) / 2.0 / h |
| 69 | + centered = _CENTER_LO <= cx <= _CENTER_HI and _CENTER_LO <= cy <= _CENTER_HI |
| 70 | + aspect = bw / bh |
| 71 | + aspect_ok = _CARD_AR_MIN <= aspect <= _CARD_AR_MAX |
| 72 | + return fill, centered, aspect_ok |
| 73 | + |
| 74 | + |
| 75 | +def assess_card_image(image_bytes: bytes) -> CardGateResult: |
| 76 | + """ |
| 77 | + Decide whether ``image_bytes`` looks like a card worth sending to OCR. |
| 78 | +
|
| 79 | + Never raises — any decode/processing error is reported as a non-card so the |
| 80 | + caller simply skips the frame (no Groq call). |
| 81 | + """ |
| 82 | + try: |
| 83 | + img = Image.open(io.BytesIO(image_bytes)) |
| 84 | + img = ImageOps.exif_transpose(img).convert("L") |
| 85 | + except Exception: # noqa: BLE001 - any malformed upload is just "not a card" |
| 86 | + return CardGateResult(False, "unreadable", 0.0, 0.0, 0.0) |
| 87 | + |
| 88 | + img.thumbnail((_ANALYZE_EDGE, _ANALYZE_EDGE)) |
| 89 | + w, h = img.size |
| 90 | + if w < 48 or h < 48: |
| 91 | + return CardGateResult(False, "too_small", 0.0, 0.0, 0.0) |
| 92 | + |
| 93 | + detail = float(ImageStat.Stat(img).stddev[0]) |
| 94 | + edges = img.filter(ImageFilter.FIND_EDGES) |
| 95 | + focus = float(ImageStat.Stat(edges).stddev[0]) |
| 96 | + fill, centered, aspect_ok = _bbox_metrics(edges, w, h) |
| 97 | + |
| 98 | + if detail < _MIN_DETAIL_STDDEV: |
| 99 | + return CardGateResult(False, "empty", detail, focus, fill) |
| 100 | + if focus < _MIN_FOCUS: |
| 101 | + return CardGateResult(False, "blurry", detail, focus, fill) |
| 102 | + if fill < _MIN_FILL or not centered or not aspect_ok: |
| 103 | + return CardGateResult(False, "no_card", detail, focus, fill) |
| 104 | + return CardGateResult(True, "ok", detail, focus, fill) |
0 commit comments