Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/ai/images.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Pipeline d'images d'annonce (§91-93, 160-163, 186-190) — SERVEUR :44 * téléchargement borné, type par octets magiques, dimensions par lecture des45 * en-têtes (sans dépendance), hash sha256, dédoublonnage, retrait des46 * miniatures, présélection ≤ MAX, manifeste transmis au modèle, cache disque47 * temporaire purgé selon LISTING_IMAGE_RETENTION_DAYS. Une photo qui échoue48 * n'arrête pas l'analyse. Les octets ne sont jamais redistribués.49 */50import { createHash } from "crypto";51import fs from "fs";52import path from "path";5354export const MAX_IMAGE_BYTES = 4.5 * 1024 * 1024;55export const MIN_IMAGE_PX = 400;56export const FETCH_TIMEOUT_MS = 20_000;5758export type ImageMediaType = "image/jpeg" | "image/png" | "image/webp" | "image/gif";5960export interface PreparedImage {61 id: string; // photo_01…62 position: number; // position d'origine dans l'annonce (1-based)63 sourceUrl: string;64 hash: string;65 width: number | null;66 height: number | null;67 bytes: number;68 mediaType: ImageMediaType;69 roomHint: string;70 qualityScore: number;71 data: Buffer;72}7374export interface ImagePipelineResult {75 selected: PreparedImage[];76 all: Omit<PreparedImage, "data">[];77 failed: { url: string; error: string }[];78 duplicatesRemoved: number;79 thumbnailsRemoved: number;80}8182export function cacheDir(uid: string): string {83 return path.join(process.cwd(), "tmp", "listing-images", uid.replace(/[^a-zA-Z0-9_:-]/g, "_"));84}8586/* ------------------------------------------------------------ détection */8788export function sniffMediaType(buf: Buffer): ImageMediaType | null {89 if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "image/jpeg";90 if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "image/png";91 if (buf.length >= 12 && buf.subarray(0, 4).toString("ascii") === "RIFF" && buf.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";92 if (buf.length >= 6 && buf.subarray(0, 3).toString("ascii") === "GIF") return "image/gif";93 return null;94}9596/** Dimensions lues dans les en-têtes JPEG (SOF), PNG (IHDR), WebP (VP8/VP8L/VP8X), GIF. */97export function readDimensions(buf: Buffer, type: ImageMediaType): { width: number; height: number } | null {98 try {99 if (type === "image/png" && buf.length >= 24) return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };100 if (type === "image/gif" && buf.length >= 10) return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };101 if (type === "image/webp" && buf.length >= 30) {102 const chunk = buf.subarray(12, 16).toString("ascii");103 if (chunk === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };104 if (chunk === "VP8L") { const b0 = buf[21], b1 = buf[22], b2 = buf[23], b3 = buf[24]; return { width: 1 + (((b1 & 0x3f) << 8) | b0), height: 1 + (((b3 & 0xf) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)) }; }105 if (chunk === "VP8X") return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };106 }107 if (type === "image/jpeg") {108 let i = 2;109 while (i + 9 < buf.length) {110 if (buf[i] !== 0xff) { i++; continue; }111 const marker = buf[i + 1];112 if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { i += 2; continue; }113 const len = buf.readUInt16BE(i + 2);114 if ((marker >= 0xc0 && marker <= 0xcf) && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };115 i += 2 + len;116 }117 }118 } catch { /* en-tête tronqué */ }119 return null;120}121122export const sha256 = (b: Buffer | string): string => createHash("sha256").update(b).digest("hex");123124/* --------------------------------------------------------------- fetch */125126/** En-têtes ASCII seulement : un octet accentué dans le User-Agent fait répondre127 * HTTP 400 aux CDN stricts (Facebook Marketplace `*.fbcdn.net`, 2026-09-08). */128const UA_BOT = "Vrai-Prix/1.0 (building analysis; +https://www.vrai-prix.com)";129const UA_BROWSER = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36";130const ACCEPT_IMG = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8";131132/** Referer plausible pour les CDN qui l'exigent (photos servies depuis un domaine distinct du site). */133export function refererFor(url: string): string {134 try {135 const h = new URL(url).hostname;136 if (/\.fbcdn\.net$|facebook\.com$/.test(h)) return "https://www.facebook.com/";137 if (/ebayimg\.com$|kijiji/.test(h)) return "https://www.kijiji.ca/";138 if (/centris\.ca$/.test(h)) return "https://www.centris.ca/";139 if (/duproprio\.com$/.test(h)) return "https://duproprio.com/";140 const parts = h.split(".");141 return `https://www.${parts.slice(-2).join(".")}/`;142 } catch {143 return "https://www.vrai-prix.com/";144 }145}146147export async function fetchImage(url: string, timeoutMs = FETCH_TIMEOUT_MS): Promise<{ data: Buffer; mediaType: ImageMediaType }> {148 const ctrl = new AbortController();149 const t = setTimeout(() => ctrl.abort(), timeoutMs);150 try {151 // 1er essai : identité déclarée (bot) ; 2e essai (4xx) : en-têtes de navigateur + Referer.152 let res = await fetch(url, { signal: ctrl.signal, headers: { "User-Agent": UA_BOT, Accept: ACCEPT_IMG }, redirect: "follow" });153 if (!res.ok && res.status >= 400 && res.status < 500) {154 res = await fetch(url, {155 signal: ctrl.signal,156 redirect: "follow",157 headers: { "User-Agent": UA_BROWSER, Accept: ACCEPT_IMG, "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8", Referer: refererFor(url), "Sec-Fetch-Dest": "image", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Site": "cross-site" },158 });159 }160 if (!res.ok) throw new Error(`HTTP ${res.status} (${new URL(url).hostname})`);161 const len = Number(res.headers.get("content-length") ?? 0);162 if (len > MAX_IMAGE_BYTES) throw new Error(`trop volumineuse (${len} octets)`);163 const ab = await res.arrayBuffer();164 if (ab.byteLength > MAX_IMAGE_BYTES) throw new Error(`trop volumineuse (${ab.byteLength} octets)`);165 const data = Buffer.from(ab);166 const mediaType = sniffMediaType(data);167 if (!mediaType) throw new Error("format d'image non reconnu");168 return { data, mediaType };169 } finally {170 clearTimeout(t);171 }172}173174/* ----------------------------------------------------------- heuristiques */175176/** Indice de pièce léger à partir de l'URL et de la position (les photos 1-3 sont presque toujours extérieures). */177export function roomHint(url: string, position: number, total: number): string {178 const u = url.toLowerCase();179 const has = (...k: string[]) => k.some((x) => u.includes(x));180 if (has("facade", "exterieur", "exterior", "front", "ext_")) return "exterior";181 if (has("cuisine", "kitchen")) return "kitchen";182 if (has("salle-de-bain", "bathroom", "sdb", "bain")) return "bathroom";183 if (has("chambre", "bedroom")) return "bedroom";184 if (has("salon", "living", "sejour")) return "living";185 if (has("sous-sol", "basement")) return "basement";186 if (has("garage")) return "garage";187 if (has("cour", "backyard", "yard", "terrasse", "deck", "piscine", "pool")) return "exterior_rear";188 if (has("plan", "floorplan")) return "floorplan";189 if (position <= 2) return "exterior";190 if (position === total && total > 8) return "exterior_rear";191 return "unknown";192}193194/** Clé de regroupement : même photo servie en plusieurs tailles (-sm/-md/-lg, w=, /thumb/). */195export function sizeAgnosticKey(url: string): string {196 return url197 .replace(/[?#].*$/, "")198 .replace(/-(xs|sm|md|lg|xl|xxl|thumb|thumbnail|small|medium|large|original)(?=\.[a-z]{3,4}$)/i, "")199 .replace(/\/(thumb|thumbs|thumbnail|small|medium|large)\//i, "/")200 .replace(/_(\d{2,4})x(\d{2,4})(?=\.[a-z]{3,4}$)/i, "")201 .toLowerCase();202}203204/** Présélection : garde les extérieurs et une couverture régulière du reste. */205export function selectImages<T extends { roomHint: string; position: number; qualityScore: number }>(imgs: T[], max: number): T[] {206 if (imgs.length <= max) return imgs;207 const ext = imgs.filter((i) => i.roomHint.startsWith("exterior") || i.roomHint === "floorplan").slice(0, Math.min(6, Math.floor(max / 4)));208 const rest = imgs.filter((i) => !ext.includes(i));209 const slots = max - ext.length;210 const picked: T[] = [];211 for (let k = 0; k < slots; k++) picked.push(rest[Math.floor((k * rest.length) / slots)]);212 return [...ext, ...picked].sort((a, b) => a.position - b.position);213}214215/* ------------------------------------------------------------- pipeline */216217export async function prepareListingImages(uid: string, urls: string[], max: number, concurrency = 6): Promise<ImagePipelineResult> {218 const dir = cacheDir(uid);219 fs.mkdirSync(dir, { recursive: true });220 const failed: { url: string; error: string }[] = [];221 const fetched: (PreparedImage & { key: string })[] = [];222 let idx = 0;223 const worker = async () => {224 while (idx < urls.length) {225 const pos = idx++;226 const url = urls[pos];227 try {228 const { data, mediaType } = await fetchImage(url);229 const hash = sha256(data);230 const dims = readDimensions(data, mediaType);231 const px = dims ? Math.min(dims.width, dims.height) : null;232 const ext = mediaType.split("/")[1];233 const cached = path.join(dir, `${hash}.${ext}`);234 if (!fs.existsSync(cached)) fs.writeFileSync(cached, data);235 fetched.push({ id: "", position: pos + 1, sourceUrl: url, hash, width: dims?.width ?? null, height: dims?.height ?? null, bytes: data.length, mediaType, roomHint: roomHint(url, pos + 1, urls.length), qualityScore: px ? Math.min(1, px / 1200) : 0.5, data, key: sizeAgnosticKey(url) });236 } catch (e) {237 failed.push({ url, error: (e as Error).message });238 }239 }240 };241 await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(1, urls.length)) }, worker));242 fetched.sort((a, b) => a.position - b.position);243 // dédoublonnage : hash identique, puis même clé d'URL (on garde la plus grande)244 const byHash = new Map<string, PreparedImage & { key: string }>();245 let duplicates = 0;246 for (const f of fetched) {247 if (byHash.has(f.hash)) { duplicates++; continue; }248 byHash.set(f.hash, f);249 }250 const byKey = new Map<string, PreparedImage & { key: string }>();251 for (const f of byHash.values()) {252 const cur = byKey.get(f.key);253 if (!cur) byKey.set(f.key, f);254 else { duplicates++; if ((f.width ?? 0) * (f.height ?? 0) > (cur.width ?? 0) * (cur.height ?? 0)) byKey.set(f.key, f); }255 }256 let unique = [...byKey.values()].sort((a, b) => a.position - b.position);257 const before = unique.length;258 unique = unique.filter((i) => i.width == null || Math.min(i.width, i.height ?? i.width) >= MIN_IMAGE_PX);259 const thumbs = before - unique.length;260 const selected = selectImages(unique, max).map((img, i) => ({ ...img, id: `photo_${String(i + 1).padStart(2, "0")}` }));261 const all = unique.map((img) => { const sel = selected.find((s) => s.hash === img.hash); const { data: _d, key: _k, ...rest } = img; void _d; void _k; return { ...rest, id: sel?.id ?? "" }; });262 return { selected: selected.map(({ key: _k, ...r }) => { void _k; return r; }), all, failed, duplicatesRemoved: duplicates, thumbnailsRemoved: thumbs };263}264265/** Purge du cache disque au-delà de la rétention (défaut 30 jours). */266export function purgeImageCache(retentionDays = Number(process.env.LISTING_IMAGE_RETENTION_DAYS ?? 30)): number {267 const root = path.join(process.cwd(), "tmp", "listing-images");268 if (!fs.existsSync(root)) return 0;269 const cutoff = Date.now() - retentionDays * 86400000;270 let n = 0;271 for (const d of fs.readdirSync(root)) {272 const p = path.join(root, d);273 try {274 const st = fs.statSync(p);275 if (st.isDirectory() && st.mtimeMs < cutoff) { fs.rmSync(p, { recursive: true, force: true }); n++; }276 } catch { /* ignore */ }277 }278 return n;279}280