SPB Git

Repository Public

img.py 6.7 KB 157 lines python

1# -----------------------------------------------------------------------------2# Food-Ka v2 — img.py : miniatures WebP en cache (GET /api/img?u=&w=)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4#5# Les photos viennent de vingt hôtes différents, en tailles et formats divers.6# On sert une miniature WebP redimensionnée, gardée sur disque7# (data/imgcache/). Seuls les hôtes dont viennent réellement les photos du8# catalogue sont acceptés (pas de relais ouvert), en https, sans redirection9# vers un autre hôte. Une photo morte est retenue 24 h pour ne pas réessayer.10# -----------------------------------------------------------------------------11from __future__ import annotations1213import hashlib14import io15import time16from pathlib import Path17from urllib.parse import urlsplit1819import requests2021ROOT = Path(__file__).resolve().parent.parent22CACHE = ROOT / "data" / "imgcache"23LARGEURS = (96, 160, 240, 320, 480, 640, 960)24HOTES_FIXES = {25    "cdn.shopify.com", "f.wishabi.net", "www.saq.com", "alimentsmerci.com",26    "digital.loblaws.ca", "assets.loblaws.ca", "product-images.metro.ca",27    "i5.walmartimages.ca", "akhavanfood.com", "bocoboco.ca", "voila.ca",28    "www.aubut.ca", "www.instacart.com", "mayrand.ca", "www.tntsupermarket.com",29    "maturin.ca", "avril.ca", "gdx-assets.costco.com",30}31MORT_TTL = 8640032TAILLE_MAX = 12 * 1024 * 102433_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36"343536class Refus(Exception):37    def __init__(self, code: int, message: str) -> None:38        super().__init__(message)39        self.code, self.message = code, message404142def largeur_valide(w: int) -> int:43    """Largeur demandée -> palier servi (le plus petit palier ≥ w)."""44    for palier in LARGEURS:45        if w <= palier:46            return palier47    return LARGEURS[-1]484950def hote_permis(host: str, hotes_catalogue: set[str]) -> bool:51    host = (host or "").lower()52    return host in HOTES_FIXES or host in hotes_catalogue535455SEUIL_BLANC = 244          # un pixel est « blanc » si ses trois canaux dépassent ce seuil565758def analyser_fond(im) -> tuple[bool, tuple[int, int, int, int] | None]:59    """(fond blanc ?, boîte englobante du sujet). Le fond est dit blanc quand60    92 % au moins des pixels du pourtour le sont (transparence = blanc)."""61    from PIL import Image62    rgba = im.convert("RGBA")63    plat = Image.new("RGB", rgba.size, (255, 255, 255))64    plat.paste(rgba, mask=rgba.split()[3])65    petit = plat.copy()66    petit.thumbnail((240, 240))67    gris = petit.convert("L").point(lambda v: 0 if v >= SEUIL_BLANC else 255)68    lw, lh = gris.size69    px = gris.load()70    bord = [px[x, y] for x in range(lw) for y in (0, lh - 1)] + \71           [px[x, y] for y in range(lh) for x in (0, lw - 1)]72    blanc = sum(1 for v in bord if v == 0) / max(len(bord), 1) >= 0.9273    boite = gris.getbbox()74    if not blanc or boite is None:75        return blanc, None76    fx, fy = plat.width / lw, plat.height / lh77    marge = round(max(plat.size) * 0.02)78    g, h, d, b = boite79    boite = (max(0, int(g * fx) - marge), max(0, int(h * fy) - marge),80             min(plat.width, int(d * fx + fx) + marge), min(plat.height, int(b * fy + fy) + marge))81    return blanc, boite828384def miniature(url: str, w: int, hotes_catalogue: set[str],85              trim: bool = False) -> tuple[bytes, bool, str]:86    """(octets WebP, servi_du_cache, fond). `fond` vaut « white », « other » ou87    « unknown ». `trim` : rogne les marges blanches à la boîte englobante du88    sujet (2 % de marge) ; une photo dont le fond n'est pas blanc n'est jamais89    rognée. Lève Refus(code, message)."""90    try:91        parts = urlsplit(url)92    except ValueError:93        raise Refus(400, "adresse invalide") from None94    if parts.scheme != "https" or not parts.hostname:95        raise Refus(400, "adresse https attendue")96    if not hote_permis(parts.hostname, hotes_catalogue):97        raise Refus(400, "hôte non autorisé")98    w = largeur_valide(int(w))99    cle = hashlib.sha1(url.encode("utf-8")).hexdigest()100    CACHE.mkdir(parents=True, exist_ok=True)101    fichier = CACHE / cle[:2] / f"{cle}_{w}{'_t' if trim else ''}.webp"102    mort = CACHE / cle[:2] / f"{cle}.mort"103    note = CACHE / cle[:2] / f"{cle}.fond"104    if fichier.is_file():105        try:106            fond = note.read_text().strip() or "unknown"107        except OSError:108            fond = "unknown"109        return fichier.read_bytes(), True, fond110    if mort.is_file() and time.time() - mort.stat().st_mtime < MORT_TTL:111        raise Refus(404, "photo indisponible à la source")112    fichier.parent.mkdir(parents=True, exist_ok=True)113    try:114        r = requests.get(url, timeout=(5, 12), stream=True, allow_redirects=False,115                         headers={"User-Agent": _UA, "Accept": "image/*"})116        saut = 0117        while r.status_code in (301, 302, 307, 308) and saut < 3:118            suite = requests.compat.urljoin(url, r.headers.get("Location", ""))119            sp = urlsplit(suite)120            if sp.scheme != "https" or not hote_permis(sp.hostname or "", hotes_catalogue):121                raise Refus(404, "redirection hors des hôtes autorisés")122            r = requests.get(suite, timeout=(5, 12), stream=True, allow_redirects=False,123                             headers={"User-Agent": _UA, "Accept": "image/*"})124            saut += 1125        if r.status_code != 200:126            raise Refus(404, f"photo indisponible à la source (HTTP {r.status_code})")127        brut = r.raw.read(TAILLE_MAX + 1, decode_content=True)128        if len(brut) > TAILLE_MAX or len(brut) < 64:129            raise Refus(404, "photo vide ou trop lourde")130        from PIL import Image131        im = Image.open(io.BytesIO(brut))132        im.load()133        if im.mode not in ("RGB", "RGBA"):134            im = im.convert("RGBA" if "A" in im.getbands() or im.mode == "P" else "RGB")135        blanc, boite = analyser_fond(im)136        fond = "white" if blanc else "other"137        note.write_text(fond)138        if trim and boite and (boite[2] - boite[0]) >= 16 and (boite[3] - boite[1]) >= 16:139            im = im.crop(boite)140        if im.width > w:141            im = im.resize((w, max(1, round(im.height * w / im.width))), Image.LANCZOS)142        tampon = io.BytesIO()143        im.save(tampon, "WEBP", quality=80, method=4)144        data = tampon.getvalue()145        tmp = fichier.with_suffix(".tmp")146        tmp.write_bytes(data)147        tmp.replace(fichier)148        return data, False, fond149    except Refus:150        mort.parent.mkdir(parents=True, exist_ok=True)151        mort.touch()152        raise153    except Exception:  # noqa: BLE001 — réseau, image illisible…154        mort.parent.mkdir(parents=True, exist_ok=True)155        mort.touch()156        raise Refus(404, "photo illisible à la source") from None157
Files main
Menu

Theme