Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/imgaudit.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1913# Last Modified : 2026-08-1914#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# imgaudit.py : qualité des images d'annonces.91#92# 1) clean_gallery(urls) — nettoyage STATIQUE (sans réseau), appliqué par93# PropertyListing.finalize() : URLs invalides, placeholders connus des94# portails (« photo à venir », logos), doublons (y compris la même photo95# en deux tailles).96# 2) run_batch(...) — audit RÉSEAU budgété des photos de couverture : lien97# mort (4xx/5xx/timeout), image minuscule/pixellisée (dimensions décodées98# de l'en-tête JPEG/PNG/WebP/GIF), fichier corrompu. Résultats en cache99# (table image_audit, TTL 30 jours). Une couverture morte est retirée et100# la première image VALIDE de la galerie est promue ; une annonce sans101# aucune image valide est marquée (details.needs_image_review) — le102# frontend affiche alors l'image de secours par type de bien.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import re108import sqlite3109import struct110import time111from concurrent.futures import ThreadPoolExecutor112113import requests114115AUDIT_TTL = 30 * 86400 # re-vérification d'une URL après 30 jours116MIN_WIDTH, MIN_HEIGHT = 250, 160 # sous ces dimensions : miniature inutilisable117MIN_BYTES = 3_000 # fichier suspicieusement petit (icône/placeholder)118TIMEOUT = 10119UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "120 "(KHTML, like Gecko) Chrome/126 Safari/537.36 ImmoKaBot/1.0")121122# motifs de placeholders/logos des portails (jamais une photo de propriété).123# ⚠ default/defaut/logo sont ANCRÉS sur le nom de fichier : un segment de124# chemin comme Cloudinary « t_default_size/ » n'est PAS un placeholder125# (bug payé : toutes les galeries Ubee vidées par « default[-_.] »).126_PLACEHOLDER_RE = re.compile(127 r"placeholder|no[-_]?photo|nophoto|photo[-_]?a[-_]?venir|coming[-_]?soon|"128 r"missing|awaiting|shadow_listing|image[-_]?indisponible|no[-_]?image|"129 r"/(?:default|defaut|logo)[^/]*\.(?:jpe?g|png|webp|gif|svg)(?:\?|$)", re.I)130131_SIZE_VARIANT_RE = re.compile(r"-(?:sm|md|lg|xl|thumb|small|medium|large)(?=\.\w+$)")132133# handlers dynamiques : la photo est identifiée par la QUERYSTRING (propId/seq,134# id…), pas par le chemin — ex. yoamo.immo/ALSPicture.axd?propId=…&seq=N,135# mediaserver.centris.ca/media.ashx?id=… On ne retire que les params de taille.136_DYNAMIC_EXT = (".axd", ".ashx", ".php", ".aspx", ".cfm")137_SIZE_PARAM_RE = re.compile(r"&(?:w|h|width|height|size|sm|scale|quality)=[^&]*", re.I)138139140def _canon(url: str) -> str:141 """Clé de déduplication : ignore la variante de taille et la querystring142 de redimensionnement pour attraper la même photo en deux formats."""143 path, _, query = url.partition("?")144 if query and path.lower().endswith(_DYNAMIC_EXT):145 params = _SIZE_PARAM_RE.sub("", "&" + query.replace("&", "&")).lstrip("&")146 return f"{path}?{params}".lower()147 return _SIZE_VARIANT_RE.sub("", path).lower()148149150def clean_gallery(urls: list[str]) -> list[str]:151 """Nettoyage statique d'une galerie : URLs http(s) uniquement, placeholders152 retirés, doublons (même photo, autre taille) dédupliqués, ordre préservé."""153 out: list[str] = []154 seen: set[str] = set()155 for u in urls or []:156 if not isinstance(u, str):157 continue158 u = u.strip()159 if not u.lower().startswith(("http://", "https://")):160 continue161 if _PLACEHOLDER_RE.search(u):162 continue163 key = _canon(u)164 if key in seen:165 continue166 seen.add(key)167 out.append(u)168 return out169170171# ---------------------------------------------------------------------------172# Décodage des dimensions depuis les premiers octets (sans télécharger tout)173# ---------------------------------------------------------------------------174175def image_size(data: bytes) -> tuple[int, int] | None:176 """(largeur, hauteur) depuis l'en-tête PNG/GIF/WebP/JPEG, None si indécodable."""177 if len(data) < 26:178 return None179 if data[:8] == b"\x89PNG\r\n\x1a\n":180 w, h = struct.unpack(">II", data[16:24])181 return w, h182 if data[:6] in (b"GIF87a", b"GIF89a"):183 w, h = struct.unpack("<HH", data[6:10])184 return w, h185 if data[:4] == b"RIFF" and data[8:12] == b"WEBP":186 if data[12:16] == b"VP8 " and len(data) >= 30:187 w, h = struct.unpack("<HH", data[26:30])188 return w & 0x3FFF, h & 0x3FFF189 if data[12:16] == b"VP8L" and len(data) >= 25:190 bits = struct.unpack("<I", data[21:25])[0]191 return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1192 if data[12:16] == b"VP8X" and len(data) >= 30:193 w = int.from_bytes(data[24:27], "little") + 1194 h = int.from_bytes(data[27:30], "little") + 1195 return w, h196 if data[:2] == b"\xff\xd8": # JPEG : chercher le SOF197 i = 2198 while i + 9 < len(data):199 if data[i] != 0xFF:200 i += 1201 continue202 marker = data[i + 1]203 if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,204 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):205 h, w = struct.unpack(">HH", data[i + 5:i + 9])206 return w, h207 seg_len = struct.unpack(">H", data[i + 2:i + 4])[0]208 i += 2 + seg_len209 return None210211212def check_url(url: str) -> dict:213 """Vérifie une URL d'image : {ok, status, width, height, bytes, reason}.214215 ⚠ Verdict « morte » UNIQUEMENT sur preuve solide (404/410) : un 403/429 est216 presque toujours du rate-limiting ou de l'anti-hotlink du CDN (bug payé :217 ~6 000 galeries DuProprio retirées à tort). En cas de doute on garde218 l'image — le repli onError du frontend couvre les rares vraies mortes."""219 try:220 r = requests.get(url, headers={"User-Agent": UA, "Range": "bytes=0-65535"},221 timeout=TIMEOUT, stream=True)222 status = r.status_code223 if status in (404, 410):224 return {"ok": 0, "status": status, "reason": "http"}225 if status >= 400:226 return {"ok": 1, "status": status, "reason": "non_verifiable"}227 data = next(r.iter_content(65536), b"") or b""228 r.close()229 total = int((r.headers.get("Content-Range") or "/0").split("/")[-1] or 0) \230 or int(r.headers.get("Content-Length") or 0) or len(data)231 size = image_size(data)232 if size is None:233 ctype = (r.headers.get("Content-Type") or "").lower()234 if "image" not in ctype:235 return {"ok": 0, "status": status, "bytes": total, "reason": "format"}236 # image valide mais en-tête non décodé (format exotique) : on tolère237 return {"ok": 1, "status": status, "bytes": total}238 w, h = size239 if w < MIN_WIDTH or h < MIN_HEIGHT:240 return {"ok": 0, "status": status, "width": w, "height": h,241 "bytes": total, "reason": "minuscule"}242 if total and total < MIN_BYTES:243 return {"ok": 0, "status": status, "width": w, "height": h,244 "bytes": total, "reason": "poids_suspect"}245 return {"ok": 1, "status": status, "width": w, "height": h, "bytes": total}246 except requests.RequestException:247 # réseau/timeout : non concluant — ne jamais retirer sur un doute248 return {"ok": 1, "status": 0, "reason": "non_verifiable"}249250251# ---------------------------------------------------------------------------252# Audit budgété des couvertures (+ galeries courtes) avec cache BD253# ---------------------------------------------------------------------------254255def _ensure_table(con: sqlite3.Connection) -> None:256 con.execute("""CREATE TABLE IF NOT EXISTS image_audit (257 url TEXT PRIMARY KEY,258 ok INTEGER,259 status INTEGER,260 width INTEGER,261 height INTEGER,262 bytes INTEGER,263 reason TEXT,264 checked_at REAL265 )""")266 con.commit()267268269def _cached(con: sqlite3.Connection, url: str) -> dict | None:270 r = con.execute("SELECT ok, reason, checked_at FROM image_audit WHERE url=?",271 (url,)).fetchone()272 if r and time.time() - (r["checked_at"] or 0) < AUDIT_TTL:273 return {"ok": r["ok"], "reason": r["reason"]}274 return None275276277def _store(con: sqlite3.Connection, url: str, res: dict) -> None:278 con.execute(279 "INSERT INTO image_audit (url, ok, status, width, height, bytes, reason,"280 " checked_at) VALUES (?,?,?,?,?,?,?,?)"281 " ON CONFLICT(url) DO UPDATE SET ok=excluded.ok, status=excluded.status,"282 " width=excluded.width, height=excluded.height, bytes=excluded.bytes,"283 " reason=excluded.reason, checked_at=excluded.checked_at",284 (url, res.get("ok"), res.get("status"), res.get("width"),285 res.get("height"), res.get("bytes"), res.get("reason"), time.time()))286287288def audit_listing(con: sqlite3.Connection, uid: str, images: list[str],289 details: dict, pool: ThreadPoolExecutor) -> tuple[list[str], dict, int]:290 """Vérifie la couverture (et remonte la 1re image valide en tête).291292 Vérifie au plus les 4 premières images ; les mortes sont retirées de la293 galerie. Retourne (nouvelle galerie, details, nb de vérifications réseau)."""294 checked = 0295 good_idx = None296 dead: set[int] = set()297 for i, url in enumerate(images[:4]):298 res = _cached(con, url)299 if res is None:300 res = check_url(url)301 _store(con, url, res)302 checked += 1303 if res.get("ok"):304 good_idx = i305 break306 dead.add(i)307 new_images = [u for i, u in enumerate(images) if i not in dead]308 details = dict(details)309 if good_idx is None and images:310 # aucune image valide parmi les premières : re-vérification demandée,311 # le frontend applique l'image de secours par type de bien312 details["needs_image_review"] = True313 else:314 details.pop("needs_image_review", None)315 return new_images, details, checked316317318def run_batch(limit: int = 2000, workers: int = 8) -> dict:319 """Audit réseau budgété : les annonces publiées jamais auditées d'abord.320321 Appelé après chaque synchronisation (ingest.watch) ; relancer avec un gros322 `limit` pour un rattrapage complet. Idempotent grâce au cache par URL."""323 from . import db324 con = db.connect()325 _ensure_table(con)326 rows = con.execute(327 "SELECT uid, images, details FROM listings"328 " WHERE active=1 AND dup_hidden=0 AND images IS NOT NULL AND images!='[]'"329 " AND json_extract(COALESCE(details,'{}'), '$.img_audited') IS NULL"330 " LIMIT ?", (limit,)).fetchall()331 checked = removed = flagged = 0332333 def _work(row):334 images = json.loads(row["images"] or "[]")335 details = json.loads(row["details"] or "{}")336 # les URLs sont vérifiées séquentiellement par annonce ; le parallélisme337 # est au niveau des annonces (une connexion BD par worker serait fragile,338 # donc le réseau seul est parallèle : cache lu/écrit dans le fil principal)339 return row["uid"], images, details340341 with ThreadPoolExecutor(max_workers=workers) as pool:342 futures = []343 for row in rows:344 uid, images, details = _work(row)345 futures.append((uid, images, details))346 # traitement principal (cache BD dans ce fil, réseau via check_url —347 # parallélisé par lots d'URLs de couverture inconnues)348 unknown = []349 for uid, images, details in futures:350 for u in images[:4]:351 if _cached(con, u) is None:352 unknown.append(u)353 unknown = list(dict.fromkeys(unknown))354 # commits par tranches : ne JAMAIS tenir le verrou d'écriture pendant355 # tout l'audit (des dizaines de minutes) — les syncs/le web écrivent aussi356 for url, res in zip(unknown, pool.map(check_url, unknown)):357 _store(con, url, res)358 checked += 1359 if checked % 400 == 0:360 con.commit()361 con.commit()362 done = 0363 for uid, images, details in futures:364 new_images, new_details, _ = audit_listing(con, uid, images, details,365 pool)366 new_details["img_audited"] = int(time.time())367 if new_details.get("needs_image_review"):368 flagged += 1369 removed += len(images) - len(new_images)370 con.execute("UPDATE listings SET images=?, details=? WHERE uid=?",371 (json.dumps(new_images, ensure_ascii=False),372 json.dumps(new_details, ensure_ascii=False), uid))373 done += 1374 if done % 400 == 0:375 con.commit()376 con.commit()377 con.close()378 return {"annonces": len(rows), "urls_verifiees": checked,379 "images_retirees": removed, "sans_image_valide": flagged}380