SPB Git

Repository Public

imgcheck.py 13.3 KB 331 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/imgcheck.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# imgcheck.py : contrôle qualité des images d'annonces91#   - liens morts (404, timeout, non-image)          -> retirés92#   - images minuscules / pixellisées                 -> retirées93#   - placeholders de la source (même image générique94#     répétée sur une grande part des annonces)       -> retirés95#   - doublons dans une même galerie (hash contenu)   -> dédupliqués96#   Résultat par annonce : listings.images_ok (galerie nettoyée, ordre97#   d'origine conservé) + listings.img_audit (JSON de traçabilité).98#   Les vérifications par URL sont mises en cache dans image_checks.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import io103import json104import hashlib105import threading106import time107from concurrent.futures import ThreadPoolExecutor108from urllib.parse import urlsplit109110import requests111112# seuils de qualité113MIN_WIDTH = 250114MIN_HEIGHT = 180115MIN_BYTES = 6_000          # en dessous : icône / pixel de tracking116MAX_DOWNLOAD = 6_000_000   # on ne lit jamais plus de 6 Mo par image117TIMEOUT = 12118RECHECK_FAILED_DAYS = 7    # une image en échec est retentée après 7 jours119120# placeholder : même contenu présent sur >= PLACEHOLDER_MIN annonces distinctes,121# >= PLACEHOLDER_RATIO des annonces actives de la source ET réparti sur122# >= PLACEHOLDER_ADDRS adresses différentes. (Les photos d'immeuble ou de123# projet partagées entre les unités d'une MÊME adresse — piscine, gym,124# façade — sont légitimes : c'est la dispersion multi-adresses qui trahit125# le visuel générique « image non disponible ».)126PLACEHOLDER_MIN = 12127PLACEHOLDER_RATIO = 0.30128PLACEHOLDER_ADDRS = 8129130_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "131       "(KHTML, like Gecko) Chrome/126 Safari/537.36 LouKaImgBot/1.0 "132       "(+https://www.lou-ka.com/bot; contact@spboucher.ai)")133134# politesse : au plus 3 téléchargements simultanés PAR HÔTE (24 threads sur un135# même CDN = refus/limitation, et des images vivantes classées mortes à tort)136_HOST_SEMS: dict[str, threading.Semaphore] = {}137_HOST_LOCK = threading.Lock()138139140def _host_sem(url: str) -> threading.Semaphore:141    host = urlsplit(url).netloc142    with _HOST_LOCK:143        if host not in _HOST_SEMS:144            _HOST_SEMS[host] = threading.Semaphore(3)145        return _HOST_SEMS[host]146147148def _check_url(url: str) -> dict:149    """Télécharge et inspecte une image. Retourne {status,width,height,bytes,sha1}."""150    out = {"url": url, "status": "dead", "width": None, "height": None,151           "bytes": None, "sha1": None}152    if not url or not url.startswith(("http://", "https://")):153        return out154    try:155        with _host_sem(url):156            resp = requests.get(url, timeout=TIMEOUT, stream=True,157                                headers={"User-Agent": _UA,158                                         "Accept": "image/*,*/*;q=0.5"})159            if resp.status_code in (404, 410):160                return out            # lien mort, définitif161            if resp.status_code >= 400:162                out["status"] = "error"   # 403/429/5xx : indéterminé, à retenter163                return out164            buf = io.BytesIO()165            for chunk in resp.iter_content(65536):166                buf.write(chunk)167                if buf.tell() > MAX_DOWNLOAD:168                    break169            data = buf.getvalue()170    except requests.RequestException:171        out["status"] = "error"           # timeout/refus réseau : indéterminé172        return out173    out["bytes"] = len(data)174    out["sha1"] = hashlib.sha1(data).hexdigest()175    ctype = (resp.headers.get("content-type") or "").lower()176    if "svg" in ctype:      # SVG : pas de dimensions bitmap — au moins pas mort177        out["status"] = "ok" if len(data) >= 500 else "small"178        return out179    try:180        from PIL import Image181        img = Image.open(io.BytesIO(data))182        img.load()183        out["width"], out["height"] = img.size184    except Exception:185        out["status"] = "dead"   # corrompue / format non décodable186        return out187    if (len(data) < MIN_BYTES or out["width"] < MIN_WIDTH188            or out["height"] < MIN_HEIGHT):189        out["status"] = "small"190    else:191        out["status"] = "ok"192    return out193194195def _placeholder_hashes(con) -> set[str]:196    """Hashes « placeholder » : contenu identique répété massivement dans une197    même source (logo générique, « image non disponible »…)."""198    totals = {r["source"]: r["n"] for r in con.execute(199        "SELECT source, COUNT(*) n FROM listings WHERE active=1 GROUP BY source")}200    rows = con.execute(201        """SELECT l.source s, c.sha1 h, COUNT(DISTINCT l.uid) n,202                  COUNT(DISTINCT COALESCE(NULLIF(l.address,''),203                        NULLIF(l.sector,''), l.uid)) addrs204           FROM listings l, json_each(l.images) j205           JOIN image_checks c ON c.url = j.value206           WHERE l.active=1 AND c.sha1 IS NOT NULL AND c.status='ok'207           GROUP BY l.source, c.sha1 HAVING n >= ?""",208        (PLACEHOLDER_MIN,)).fetchall()209    out = set()210    for r in rows:211        if (r["n"] >= max(PLACEHOLDER_MIN, PLACEHOLDER_RATIO * totals.get(r["s"], 0))212                and r["addrs"] >= PLACEHOLDER_ADDRS):213            out.add(r["h"])214    return out215216217def run(limit_listings: int = 1500, workers: int = 24,218        source: str | None = None) -> dict:219    """Audite les images des annonces publiées sans audit (ou invalidées).220221    Incrémental : chaque appel traite au plus `limit_listings` annonces ;222    la boucle `watch` en fait avancer un lot à chaque cycle.223    """224    from . import db225    con = db.connect()226    now = time.time()227    sql = ("SELECT uid, source, images FROM listings"228           " WHERE active=1 AND published=1 AND img_audit IS NULL"229           " AND images IS NOT NULL AND images NOT IN ('[]','null')")230    args: list = []231    if source:232        sql += " AND source=?"233        args.append(source)234    sql += " ORDER BY last_seen DESC LIMIT ?"235    args.append(limit_listings)236    listings = con.execute(sql, args).fetchall()237    if not listings:238        con.close()239        return {"listings": 0}240241    # 1) URLs à vérifier (absentes du cache, ou en échec depuis > 7 jours)242    all_urls: list[str] = []243    per_listing: list[tuple[str, str, list[str]]] = []244    for r in listings:245        try:246            imgs = [u for u in json.loads(r["images"]) if isinstance(u, str)]247        except ValueError:248            imgs = []249        per_listing.append((r["uid"], r["source"], imgs))250        all_urls.extend(imgs)251    uniq = list(dict.fromkeys(all_urls))252    cached: dict[str, dict] = {}253    for i in range(0, len(uniq), 500):254        chunk = uniq[i:i + 500]255        q = ",".join("?" * len(chunk))256        for row in con.execute(257                f"SELECT * FROM image_checks WHERE url IN ({q})", chunk):258            d = dict(row)259            stale = (d["status"] != "ok"260                     and now - (d["checked_at"] or 0) > RECHECK_FAILED_DAYS * 86400)261            if not stale:262                cached[d["url"]] = d263    todo = [u for u in uniq if u not in cached]264265    # 2) vérification parallèle PUIS écriture en rafale : jamais de transaction266    #    d'écriture ouverte pendant les téléchargements (verrou SQLite sinon267    #    tenu de longues secondes → « database is locked » pour les syncs)268    checked = 0269    if todo:270        with ThreadPoolExecutor(max_workers=workers) as pool:271            for i in range(0, len(todo), 400):272                chunk_res = list(pool.map(_check_url, todo[i:i + 400]))273                for res in chunk_res:274                    cached[res["url"]] = res275                con.executemany(276                    "INSERT OR REPLACE INTO image_checks"277                    " (url, status, width, height, bytes, sha1, checked_at)"278                    " VALUES (?,?,?,?,?,?,?)",279                    [(r["url"], r["status"], r["width"], r["height"],280                      r["bytes"], r["sha1"], now) for r in chunk_res])281                con.commit()282                checked += len(chunk_res)283284    placeholders = _placeholder_hashes(con)285286    # 3) galerie nettoyée par annonce287    stats = {"listings": len(per_listing), "urls_verifiees": checked,288             "dead": 0, "small": 0, "dup": 0, "placeholder": 0,289             "galeries_videes": 0}290    for uid, _src, imgs in per_listing:291        kept, seen_hashes = [], set()292        audit = {"n": len(imgs), "dead": 0, "small": 0, "dup": 0,293                 "placeholder": 0, "ts": int(now)}294        for u in imgs:295            c = cached.get(u)296            if c is None:          # non vérifiée (réseau) : bénéfice du doute297                kept.append(u)298                continue299            if c["status"] == "dead":300                audit["dead"] += 1301                continue302            if c["status"] == "error":    # indéterminé : bénéfice du doute303                audit["uncertain"] = audit.get("uncertain", 0) + 1304                kept.append(u)305                continue306            if c["status"] == "small":307                audit["small"] += 1308                continue309            if c["sha1"] and c["sha1"] in placeholders:310                audit["placeholder"] += 1311                continue312            if c["sha1"] and c["sha1"] in seen_hashes:313                audit["dup"] += 1314                continue315            if c["sha1"]:316                seen_hashes.add(c["sha1"])317            kept.append(u)318        audit["kept"] = len(kept)319        for k in ("dead", "small", "dup", "placeholder"):320            stats[k] += audit[k]321        if not kept and imgs:322            stats["galeries_videes"] += 1323        con.execute(324            "UPDATE listings SET images_ok=?, img_audit=? WHERE uid=?",325            (json.dumps(kept, ensure_ascii=False),326             json.dumps(audit, ensure_ascii=False), uid))327    con.commit()328    con.close()329    print(f"[lou-ka] imgcheck: {stats}")330    return stats331
Files main
Menu

Theme