Repository Public
1# -----------------------------------------------------------------------------2# Fabri-Ka v2 — recherche unifiée, filtres, facettes, diversité3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# recherche.py : tout se calcule sur le catalogue en mémoire (public.py) ;5# aucune requête SQL, aucune écriture.6# -----------------------------------------------------------------------------7from __future__ import annotations89import math10import time11from urllib.parse import quote1213import numpy as np1415from . import categories as cats16from . import texte17from .public import NOUVEAU_JOURS, Catalogue1819TRIS = ("pertinence", "recent", "price_asc", "price_desc", "discount", "random")20ORIGINES = {"fabricant": (0, 1, 2), "certifie": (1,), "collectif": (2,), "revendeur": (3,)}21ORIGINE_LIBELLE = {0: "fabricant", 1: "certifie", 2: "collectif", 3: "revendeur"}22ORIGINE_TEXTE = {23 "fabricant": "Fabricant ou artisan établi au Québec",24 "certifie": "Fabricant québécois certifié",25 "collectif": "Collectif d'artisans québécois",26 "revendeur": "Détaillant québécois (revend aussi des produits d'ailleurs)",27}28TRANCHES = [(0, 10), (10, 25), (25, 50), (50, 100), (100, 250), (250, 1000), (1000, None)]29DIVERSITE_DEFAUT = 3 # produits d'une même boutique par « tour »30DIVERSITE_FENETRE = 6000 # la diversité s'applique aux N premiers résultats313233class Erreur(ValueError):34 """Paramètre invalide → 400."""353637def _csv(v) -> list[str]:38 return [x.strip() for x in str(v).split(",") if x.strip()] if v not in (None, "") else []394041def _num(v, nom):42 if v in (None, ""):43 return None44 try:45 x = float(v)46 except (TypeError, ValueError):47 raise Erreur(f"{nom} : nombre attendu")48 if math.isnan(x) or math.isinf(x):49 raise Erreur(f"{nom} : nombre attendu")50 return x515253def _flag(v) -> bool:54 return str(v or "").strip().lower() in ("1", "true", "oui", "yes", "on")555657PARAMS = ("q", "category", "subcategory", "region", "city", "store", "price_min", "price_max",58 "in_stock", "new", "days_max", "on_sale", "made_in_quebec", "origin", "platform")596061class Filtres:62 """Filtres normalisés d'une recherche. Catégories, régions, villes et63 boutiques s'écrivent par leur clé, leur nom ou leur slug."""6465 def __init__(self, cat: Catalogue, p: dict):66 g = lambda k: p.get(k) # noqa: E73167 self.q = " ".join(str(g("q") or "").split())[:120]68 self.category: list[str] = []69 for x in _csv(g("category")):70 k = cats.CLE_DU_SLUG.get(texte.slug(x)) or (x if x in cats.CATEGORIES else None)71 if k is None:72 k = next((c for c, lab in cats.LIBELLES.items() if texte.plier(lab) == texte.plier(x)), None)73 if k is None:74 raise Erreur(f"category : « {x} » inconnue")75 self.category.append(k)76 self.subcategory: list[int] = []77 for x in _csv(g("subcategory")):78 s = texte.slug(x)79 found = [j for j, d in enumerate(cat.sous)80 if d["slug"] == s and (not self.category or d["category"] in self.category)]81 if not found:82 found = [j for j, d in enumerate(cat.sous) if texte.slug(d["label"]) == s83 and (not self.category or d["category"] in self.category)]84 if not found:85 raise Erreur(f"subcategory : « {x} » inconnue")86 self.subcategory += found87 self.region: list[int] = []88 for x in _csv(g("region")):89 r = cat.region_slug.get(texte.slug(x))90 if r is None:91 raise Erreur(f"region : « {x} » inconnue")92 self.region.append(cat.region_index[r])93 self.city: list[int] = []94 for x in _csv(g("city")):95 v = cat.ville_slug.get(texte.slug(x))96 if v is None:97 raise Erreur(f"city : « {x} » inconnue")98 self.city.append(cat.ville_index[v])99 self.store: list[int] = []100 for x in _csv(g("store")):101 j = cat.b_index.get(x.lower())102 if j is None:103 raise Erreur(f"store : « {x} » inconnue ou non publique")104 self.store.append(j)105 self.price_min = _num(g("price_min"), "price_min")106 self.price_max = _num(g("price_max"), "price_max")107 self.in_stock = _flag(g("in_stock"))108 self.new = _flag(g("new"))109 d = _num(g("days_max"), "days_max")110 self.days_max = int(d) if d and d > 0 else None111 self.on_sale = _flag(g("on_sale"))112 self.origin: list[int] = []113 for x in _csv(g("origin")):114 if x not in ORIGINES:115 raise Erreur("origin : fabricant, certifie, collectif ou revendeur")116 self.origin += list(ORIGINES[x])117 if _flag(g("made_in_quebec")) and not self.origin:118 self.origin = [0, 1, 2]119 self.platform = [x.lower() for x in _csv(g("platform"))]120121 def cle(self) -> tuple:122 return (self.q.lower(), tuple(self.category), tuple(self.subcategory), tuple(self.region),123 tuple(self.city), tuple(self.store), self.price_min, self.price_max, self.in_stock,124 self.new, self.days_max, self.on_sale, tuple(self.origin), tuple(self.platform))125126 def vide(self) -> bool:127 return self.cle() == Filtres.__new__(Filtres)._cle_vide()128129 @staticmethod130 def _cle_vide():131 return ("", (), (), (), (), (), None, None, False, False, None, False, (), ())132133 def echo(self, cat: Catalogue) -> dict:134 out: dict = {}135 if self.q:136 out["q"] = self.q137 if self.category:138 out["category"] = self.category139 if self.subcategory:140 out["subcategory"] = sorted({cat.sous[j]["slug"] for j in self.subcategory})141 if self.region:142 out["region"] = [cat.regions[i] for i in self.region]143 if self.city:144 out["city"] = [cat.villes[i] for i in self.city]145 if self.store:146 out["store"] = [cat.boutiques[j]["id"] for j in self.store]147 for k in ("price_min", "price_max", "days_max"):148 if getattr(self, k) is not None:149 out[k] = getattr(self, k)150 for k in ("in_stock", "new", "on_sale"):151 if getattr(self, k):152 out[k] = True153 if self.origin:154 out["origin"] = sorted({ORIGINE_LIBELLE[i] for i in self.origin})155 if self.platform:156 out["platform"] = self.platform157 return out158159160def masques(cat: Catalogue, f: Filtres, score=None, fort=None) -> dict[str, np.ndarray]:161 """Un masque booléen par dimension active (pour les facettes à exclusion).162 `fort` (tri autre que la pertinence) : seuls les produits qui répondent par163 leur nom, leur type ou leurs étiquettes — pas tout le catalogue d'une164 boutique dont le NOM contient le mot cherché."""165 m: dict[str, np.ndarray] = {}166 S = len(cat.boutiques)167 if score is not None:168 m["q"] = fort if (fort is not None and fort.any()) else (score > 0)169 if f.category:170 m["category"] = np.isin(cat.p_cat, [cats.INDEX_CLE[k] for k in f.category])171 if f.subcategory:172 m["subcategory"] = np.isin(cat.p_sous, f.subcategory)173 if f.region:174 sm = np.isin(cat.b_region, f.region)175 m["region"] = sm[cat.p_b]176 if f.city:177 sm = np.isin(cat.b_ville, f.city)178 m["city"] = sm[cat.p_b]179 if f.store:180 sm = np.zeros(S, bool); sm[f.store] = True181 m["store"] = sm[cat.p_b]182 if f.price_min is not None or f.price_max is not None:183 pm = np.ones(cat.N, bool)184 if f.price_min is not None:185 pm &= cat.p_prix >= f.price_min186 if f.price_max is not None:187 pm &= cat.p_prix <= f.price_max188 m["price"] = pm189 if f.in_stock:190 m["in_stock"] = cat.p_dispo == 1191 if f.new:192 m["new"] = cat.p_nouveau193 if f.days_max:194 m["days_max"] = cat.p_vu >= cat.genere - f.days_max * 86400195 if f.on_sale:196 m["on_sale"] = ~np.isnan(cat.p_avant)197 if f.origin:198 sm = np.isin(cat.b_origine, f.origin)199 m["origin"] = sm[cat.p_b]200 if f.platform:201 sm = np.array([b["platform"] in f.platform for b in cat.boutiques], bool)202 m["platform"] = sm[cat.p_b]203 return m204205206def _et(m: dict, sauf: str | None = None, n: int = 0) -> np.ndarray:207 out = None208 for k, v in m.items():209 if k == sauf:210 continue211 out = v.copy() if out is None else (out & v)212 return np.ones(n, bool) if out is None else out213214215def diversifier(cat: Catalogue, ordre: np.ndarray, plafond: int) -> np.ndarray:216 """Réordonne pour qu'aucune boutique ne domine : les `plafond` premiers217 produits de chaque boutique d'abord (dans l'ordre d'origine), puis les218 `plafond` suivants, etc. Stable, donc compatible avec la pagination.219 Appliqué aux DIVERSITE_FENETRE premiers résultats ; la suite garde son ordre."""220 if plafond <= 0 or len(ordre) < 2:221 return ordre222 tete, queue = ordre[:DIVERSITE_FENETRE], ordre[DIVERSITE_FENETRE:]223 b = cat.p_b[tete]224 tri = np.argsort(b, kind="stable")225 bs = b[tri]226 debut = np.r_[0, np.flatnonzero(bs[1:] != bs[:-1]) + 1]227 longueurs = np.diff(np.r_[debut, len(bs)])228 rang = np.arange(len(bs)) - np.repeat(debut, longueurs)229 tour = np.empty(len(bs), np.int32)230 tour[tri] = rang // plafond231 final = np.lexsort((np.arange(len(tete)), tour))232 return np.r_[tete[final], queue] if len(queue) else tete[final]233234235def slug_v1(t: str) -> str:236 """Slug des adresses de produit, IDENTIQUE à celui de la v1 (les adresses237 publiques existantes restent canoniques)."""238 import re239 import unicodedata240 t = unicodedata.normalize("NFKD", t or "")241 t = "".join(c for c in t if not unicodedata.combining(c))242 return re.sub(r"[^a-z0-9]+", "-", t.lower()).strip("-")243244245def chemin_produit(uid: str, titre: str) -> str:246 s = slug_v1(titre)[:70].rstrip("-")247 return f"/produits/{s}-{uid}" if s else f"/produits/{uid}"248249250def carte(cat: Catalogue, i: int) -> dict:251 """Carte d'un produit : tout ce qu'il faut pour une vignette de liste."""252 b = cat.boutiques[int(cat.p_b[i])]253 k = cats.CLES[int(cat.p_cat[i])]254 j = int(cat.p_sous[i])255 prix = round(float(cat.p_prix[i]), 2)256 pmax = round(float(cat.p_prix_max[i]), 2)257 avant = cat.p_avant[i]258 d = int(cat.p_dispo[i])259 uid = cat.uid[i]260 out = {261 "uid": uid, "title": cat.titre[i],262 "price": prix, "price_max": pmax if pmax > prix else None,263 "compare_at_price": None if np.isnan(avant) else round(float(avant), 2),264 "discount_pct": None if np.isnan(avant) else int(round((1 - prix / float(avant)) * 100)),265 "currency": "CAD",266 "available": None if d < 0 else bool(d),267 "img": cat.img[i], "n_img": int(cat.p_nimg[i]),268 "category": k, "category_label": cats.LIBELLES[k], "category_slug": cats.SLUGS[k],269 "subcategory": cat.sous[j]["slug"] if j >= 0 else None,270 "subcategory_label": cat.sous[j]["label"] if j >= 0 else None,271 "store_id": b["id"], "store_name": b["name"], "city": b["city"] or None,272 "region": b["region"] or None, "origin": b["origin"],273 "first_seen": round(float(cat.p_vu[i]), 1),274 "days_listed": max(0, int((cat.genere - float(cat.p_vu[i])) // 86400)),275 "is_new": bool(cat.p_nouveau[i]),276 "variants_grouped": int(cat.p_nvar[i]),277 "url": cat.url[i],278 "path": chemin_produit(uid, cat.titre[i]),279 "store_path": "/boutiques/" + quote(b["id"]),280 }281 return out282283284def _ordre(cat: Catalogue, idx: np.ndarray, tri: str, score, graine: int | None) -> np.ndarray:285 if tri == "pertinence" and score is not None:286 s = score[idx].astype(np.float64)287 # à pertinence voisine : en stock, puis plus récent (idx croît avec l'âge)288 s = s * (1.0 + 0.04 * (cat.p_dispo[idx] == 1)) - idx * 1e-9289 return idx[np.argsort(-s, kind="stable")]290 if tri == "price_asc":291 return idx[np.argsort(cat.p_prix[idx], kind="stable")]292 if tri == "price_desc":293 return idx[np.argsort(-cat.p_prix[idx], kind="stable")]294 if tri == "discount":295 r = np.where(np.isnan(cat.p_avant[idx]), 0.0, 1.0 - cat.p_prix[idx] / cat.p_avant[idx])296 return idx[np.argsort(-r, kind="stable")]297 if tri == "random":298 rng = np.random.default_rng(graine or 0)299 return idx[rng.permutation(len(idx))]300 return idx # « recent » : le catalogue est déjà rangé du plus récent au plus ancien301302303def points(cat: Catalogue, idx: np.ndarray) -> tuple[list, int]:304 """Points de carte : un par BOUTIQUE ayant des résultats.305 Format : [store_id, lat, lng, n, name, city]."""306 n_b = np.bincount(cat.p_b[idx], minlength=len(cat.boutiques))307 out, sans = [], 0308 for j in np.flatnonzero(n_b):309 b = cat.boutiques[int(j)]310 if b["lat"] is None:311 sans += int(n_b[j])312 continue313 out.append([b["id"], b["lat"], b["lng"], int(n_b[j]), b["name"], b["city"] or None])314 out.sort(key=lambda p: -p[3])315 return out, sans316317318def facettes(cat: Catalogue, f: Filtres, m: dict) -> dict:319 """Comptes par dimension, chacune calculée SANS son propre filtre (on peut320 donc changer de région sans que les autres régions tombent à zéro)."""321 N = cat.N322 S = len(cat.boutiques)323 out: dict = {}324 sel = _et(m, "category", N)325 cc = np.bincount(cat.p_cat[sel], minlength=len(cats.CLES))326 out["categories"] = [{"key": k, "label": cats.LIBELLES[k], "slug": cats.SLUGS[k], "n": int(cc[i])}327 for i, k in enumerate(cats.CLES) if cc[i]]328 out["categories"].sort(key=lambda d: -d["n"])329 sel = _et(m, "subcategory", N)330 if f.category or f.q:331 sc = np.bincount(cat.p_sous[sel & (cat.p_sous >= 0)], minlength=len(cat.sous))332 out["subcategories"] = sorted(333 ({"slug": cat.sous[j]["slug"], "label": cat.sous[j]["label"],334 "category": cat.sous[j]["category"], "n": int(sc[j])}335 for j in np.flatnonzero(sc)336 if not f.category or cat.sous[j]["category"] in f.category),337 key=lambda d: -d["n"])[:40]338 else:339 out["subcategories"] = []340 sel = _et(m, "region", N)341 nb = np.bincount(cat.p_b[sel], minlength=S)342 rc = np.bincount(cat.b_region[cat.b_region >= 0], weights=nb[cat.b_region >= 0],343 minlength=len(cat.regions))344 rs = np.bincount(cat.b_region[(cat.b_region >= 0) & (nb > 0)], minlength=len(cat.regions))345 out["regions"] = sorted(({"name": r, "slug": texte.slug(r), "n": int(rc[i]), "stores": int(rs[i])}346 for i, r in enumerate(cat.regions) if rc[i]), key=lambda d: -d["n"])347 out["region_unknown"] = int(nb[cat.b_region < 0].sum())348 sel = _et(m, "city", N)349 nb = np.bincount(cat.p_b[sel], minlength=S)350 vc = np.bincount(cat.b_ville[cat.b_ville >= 0], weights=nb[cat.b_ville >= 0],351 minlength=len(cat.villes))352 top = np.argsort(-vc)[:40]353 out["cities"] = [{"name": cat.villes[int(i)], "slug": texte.slug(cat.villes[int(i)]), "n": int(vc[i])}354 for i in top if vc[i]]355 sel = _et(m, "store", N)356 nb = np.bincount(cat.p_b[sel], minlength=S)357 top = np.argsort(-nb)[:40]358 out["stores"] = [{"id": cat.boutiques[int(j)]["id"], "name": cat.boutiques[int(j)]["name"],359 "n": int(nb[j])} for j in top if nb[j]]360 out["stores_total"] = int((nb > 0).sum())361 sel = _et(m, "price", N)362 pr = cat.p_prix[sel]363 out["price"] = {"min": round(float(pr.min()), 2) if len(pr) else None,364 "max": round(float(pr.max()), 2) if len(pr) else None,365 "median": round(float(np.median(pr)), 2) if len(pr) else None,366 "buckets": [{"min": a, "max": b,367 "n": int(((pr >= a) & (pr < (b if b is not None else 9e18))).sum())}368 for a, b in TRANCHES]}369 sel = _et(m, "origin", N)370 oc = np.bincount(cat.b_origine[cat.p_b[sel]], minlength=4)371 out["origins"] = [{"key": ORIGINE_LIBELLE[i], "label": ORIGINE_TEXTE[ORIGINE_LIBELLE[i]], "n": int(oc[i])}372 for i in range(4) if oc[i]]373 out["made_in_quebec"] = int(oc[0] + oc[1] + oc[2])374 tout = _et(m, None, N)375 out["in_stock"] = int((_et(m, "in_stock", N) & (cat.p_dispo == 1)).sum())376 out["new"] = int((_et(m, "new", N) & cat.p_nouveau).sum())377 out["on_sale"] = int((_et(m, "on_sale", N) & ~np.isnan(cat.p_avant)).sum())378 out["total"] = int(tout.sum())379 return out380381382def rechercher(cat: Catalogue, f: Filtres, tri: str = "", page: int = 1, taille: int = 24,383 plafond: int | None = None, avec_points: bool = False, avec_facettes: bool = False,384 graine: int | None = None, prefixe_final: bool = False) -> dict:385 if tri and tri not in TRIS:386 raise Erreur("sort : " + ", ".join(TRIS))387 tri = tri or ("pertinence" if f.q else "recent")388 if tri == "pertinence" and not f.q:389 tri = "recent"390 page = max(1, int(page))391 taille = max(1, min(60, int(taille)))392 score, fort, diag = (cat.chercher(f.q, prefixe_final) if f.q else (None, None, None))393 m = masques(cat, f, score, fort if tri != "pertinence" else None)394 sel = _et(m, None, cat.N)395 idx = np.flatnonzero(sel)396 if tri == "random" and graine is None:397 graine = int(time.time()) % 1_000_000398 ordre = _ordre(cat, idx, tri, score, graine)399 if plafond is None:400 plafond = 0 if (len(f.store) == 1 or tri in ("price_asc", "price_desc")) else DIVERSITE_DEFAUT401 if plafond:402 ordre = diversifier(cat, ordre, plafond)403 total = int(len(ordre))404 debut = (page - 1) * taille405 out = {406 "total": total, "page": page, "page_size": taille,407 "pages": max(1, math.ceil(total / taille)), "sort": tri,408 "diversity": plafond, "stores_total": int(len(np.unique(cat.p_b[idx]))) if total else 0,409 "filters": f.echo(cat), "generated_at": round(cat.genere, 1),410 "products": [carte(cat, int(i)) for i in ordre[debut:debut + taille]],411 }412 if tri == "random":413 out["seed"] = graine414 if diag is not None:415 out["search"] = diag416 if avec_points:417 pts, sans = points(cat, idx)418 out["points_format"] = ["store_id", "lat", "lng", "n", "name", "city"]419 out["points"] = pts420 out["unpositioned"] = sans421 if avec_facettes:422 out["facets"] = facettes(cat, f, m)423 return out424