SPB Git

Repository Public

web.py 83.2 KB 1,769 lines python

1# -----------------------------------------------------------------------------2# Fabri-Ka v2 — API publique (FastAPI)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# web.py : API v2 sous /api/**, pensée pour une interface web ET une app iOS.5#   Application autonome : aucun compte, aucune session, aucun témoin.6#   Lecture seule sur la base de collecte ; la seule écriture de la v2 est sa7#   propre file d'inscriptions (var/inscriptions.db) et son cache de miniatures.8# -----------------------------------------------------------------------------9from __future__ import annotations1011import hashlib12import io13import json14import math15import os16import random17import re18import threading19import time20from pathlib import Path21from urllib.parse import quote, urlsplit2223import numpy as np24from fastapi import FastAPI, HTTPException, Request25from fastapi.middleware.cors import CORSMiddleware26from fastapi.middleware.gzip import GZipMiddleware27from fastapi.responses import JSONResponse, Response2829from . import __version__, categories as cats, inscriptions, public, recherche, texte30from .public import Catalogue, catalogue31from .recherche import Erreur, Filtres3233ROOT = Path(__file__).resolve().parent.parent34VAR = Path(os.environ.get("FABRIKA_VAR") or ROOT / "var")35NOINDEX = os.environ.get("FABRIKA_NOINDEX", "").strip() not in ("", "0", "false")36BASE = os.environ.get("FABRIKA_BASE_URL", "https://www.fabri-ka.com").rstrip("/")37CONTACT = "contact@spboucher.ai"38REVISION = 4            # révision du contrat (docs/API.md, « Changements pour les clients »)3940app = FastAPI(title="Fabri-Ka API", version=__version__, docs_url="/api/docs",41              openapi_url="/api/openapi.json")42app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST", "OPTIONS"],43                   allow_headers=["*"], max_age=86400)44app.add_middleware(GZipMiddleware, minimum_size=1024)45app.include_router(inscriptions.router)464748class _Head:49    """Répond aux requêtes HEAD comme à un GET sans corps (robots, apps, sondes)."""5051    def __init__(self, app_):52        self.app = app_5354    async def __call__(self, scope, receive, send):55        if scope["type"] != "http" or scope.get("method") != "HEAD":56            return await self.app(scope, receive, send)57        scope = dict(scope, method="GET")5859        async def envoi(message):60            if message["type"] == "http.response.body":61                message = {"type": "http.response.body", "body": b"", "more_body": False}62            await send(message)63        await self.app(scope, receive, envoi)646566app.add_middleware(_Head)676869@app.middleware("http")70async def _entetes(request: Request, call_next):71    t0 = time.perf_counter()72    resp = await call_next(request)73    resp.headers["Server-Timing"] = f"app;dur={(time.perf_counter() - t0) * 1000:.1f}"74    if NOINDEX:75        resp.headers["X-Robots-Tag"] = "noindex, nofollow"76    resp.headers.setdefault("X-Content-Type-Options", "nosniff")77    return resp787980@app.exception_handler(Erreur)81async def _erreur_param(request: Request, exc: Erreur):82    return JSONResponse({"detail": str(exc)}, status_code=400)838485def _json(payload, status: int = 200, max_age: int = 120) -> Response:86    return Response(json.dumps(payload, ensure_ascii=False, separators=(",", ":")),87                    status_code=status, media_type="application/json",88                    headers={"Cache-Control": f"public, max-age={max_age}"})899091# -- mémoïsation liée à l'instantané du catalogue ---------------------------------92_MEMO: dict = {}93_MEMO_MAX = 60094_MEMO_LOCK = threading.Lock()959697def _memo(cat: Catalogue, espace: str, clef, fabrique):98    # la clé porte l'instant de construction du catalogue, pas id(cat) : l'identité99    # d'un objet libéré peut être réattribuée, et un catalogue neuf aurait alors100    # relu les réponses d'un ancien101    k = (cat.genere, espace, clef)102    v = _MEMO.get(k)103    if v is not None:104        return v105    v = fabrique()106    with _MEMO_LOCK:107        if len(_MEMO) >= _MEMO_MAX:108            vivant = cat.genere109            for kk in [kk for kk in _MEMO if kk[0] != vivant]:110                _MEMO.pop(kk, None)111            if len(_MEMO) >= _MEMO_MAX:112                for kk in list(_MEMO)[: _MEMO_MAX // 3]:113                    _MEMO.pop(kk, None)114        _MEMO[k] = v115    return v116117118def _params(request: Request) -> dict:119    return {k: request.query_params.get(k) for k in recherche.PARAMS}120121122def _entier(v, defaut: int, mini: int, maxi: int, nom: str) -> int:123    if v in (None, ""):124        return defaut125    try:126        x = int(v)127    except (TypeError, ValueError):128        raise Erreur(f"{nom} : entier attendu")129    return max(mini, min(maxi, x))130131132# =============================================================================133# Version, règle « public »134# =============================================================================135_ETAT = {"pret": False, "erreur": None, "depuis": time.time()}136137138@app.get("/api/version")139def api_version():140    """Identité de l'API. Répond tout de suite, même pendant le premier141    chargement du catalogue (`ready: false`)."""142    out = {"api": 2, "revision": REVISION, "version": __version__, "name": "Fabri-Ka",143           "description": "Répertoire des produits et des boutiques en ligne du Québec.",144           "contact": CONTACT, "ready": _ETAT["pret"], "noindex": NOINDEX,145           "accounts": False, "rules": public.REGLES}146    if _ETAT["pret"]:147        cat = catalogue()148        out.update({"products": cat.N, "stores": len(cat.boutiques),149                    "generated_at": round(cat.genere, 1),150                    "last_collect_at": cat.derniere_passe})151    if _ETAT["erreur"]:152        out["error"] = _ETAT["erreur"]153    return _json(out, max_age=30)154155156@app.get("/api/public")157def api_public():158    """La règle « public », ses seuils et ce qu'elle écarte, mesuré."""159    cat = catalogue()160    m = cat.mesures161    return _json({162        "rules": public.REGLES,163        "thresholds": {"freshness_days": public.FRAICHEUR_JOURS, "price_min": public.PRIX_MIN,164                       "price_max": public.PRIX_MAX, "shared_photo": public.PHOTO_PARTAGEE,165                       "new_days": public.NOUVEAU_JOURS, "origins": list(public.ORIGINES_ADMISES)},166        "products": {"in_database": m["produits_base"], "active": m["produits_actifs"],167                     "public": m["produits_publics"], "excluded": m["exclus_total"],168                     "grouped": m["produits_regroupes"]},169        "excluded": [{"reason": k, "label": public.RAISONS.get(k, k), "n": v}170                     for k, v in m["exclus"].items()],171        "stores": {"registry": m["boutiques_registre"], "public": m["boutiques_publiques"],172                   "directory_only": m["boutiques_annuaire"],173                   "followed_without_public_product": m["boutiques_suivies_sans_produit_public"],174                   "excluded": [{"reason": k, "label": public.RAISONS.get(k, k), "n": v}175                                for k, v in m["boutiques_exclues"].items()],176                   "without_region": m["boutiques_sans_region"],177                   "region_inferred": m["regions_deduites"],178                   "without_position": m["boutiques_sans_position"]},179        "categorisation": {"method": m["categorisation"], "changed_from_collect": m["categories_corrigees"]},180        "made_in_quebec": {181            "meaning": "Fabri-Ka sait qu'une BOUTIQUE est établie au Québec et répertoriée par un "182                       "organisme québécois ; il ne sait pas, produit par produit, où l'objet a été "183                       "fabriqué. `origin` décrit donc la boutique : fabricant, certifie, collectif "184                       "ou revendeur.",185            "labels": recherche.ORIGINE_TEXTE},186        "generated_at": round(cat.genere, 1), "build_seconds": m["construction_s"],187    })188189190# =============================================================================191# Recherche, comptes, facettes, suggestions192# =============================================================================193def reponse_recherche(cat: Catalogue, p: dict, sort: str = "", page=1, page_size=24,194                      diversity=None, points=False, facets=False, seed=None) -> dict:195    f = Filtres(cat, p)196    clef = (f.cle(), sort, page, page_size, diversity, points, facets, seed)197    if sort == "random" and seed is None:198        return recherche.rechercher(cat, f, sort, page, page_size, diversity, points, facets, seed)199    return _memo(cat, "search", clef, lambda: recherche.rechercher(200        cat, f, sort, page, page_size, diversity, points, facets, seed))201202203@app.get("/api/search")204def search(request: Request):205    qp = request.query_params206    cat = catalogue()207    div = qp.get("diversity")208    out = reponse_recherche(209        cat, _params(request), qp.get("sort") or "",210        _entier(qp.get("page"), 1, 1, 100000, "page"),211        _entier(qp.get("page_size"), 24, 1, 60, "page_size"),212        None if div in (None, "") else _entier(div, 3, 0, 50, "diversity"),213        recherche._flag(qp.get("points")), recherche._flag(qp.get("facets")),214        None if qp.get("seed") in (None, "") else _entier(qp.get("seed"), 0, 0, 2**31 - 1, "seed"))215    return _json(out, max_age=60)216217218@app.get("/api/count")219def count(request: Request):220    cat = catalogue()221    f = Filtres(cat, _params(request))222223    def calc():224        score, _f, _d = cat.chercher(f.q) if f.q else (None, None, None)225        sel = recherche._et(recherche.masques(cat, f, score), None, cat.N)226        return {"total": int(sel.sum()), "stores": int(len(np.unique(cat.p_b[sel])))}227    return _json(_memo(cat, "count", f.cle(), calc), max_age=60)228229230@app.get("/api/facets")231def facets(request: Request):232    cat = catalogue()233    f = Filtres(cat, _params(request))234235    def calc():236        score, _f, _d = cat.chercher(f.q) if f.q else (None, None, None)237        out = recherche.facettes(cat, f, recherche.masques(cat, f, score))238        out["filters"] = f.echo(cat)239        return out240    return _json(_memo(cat, "facets", f.cle(), calc), max_age=120)241242243def _suggestions(cat: Catalogue, q: str, limite: int) -> dict:244    p = texte.plier(q)245    out = {"q": q, "categories": [], "subcategories": [], "stores": [], "cities": [],246           "regions": [], "terms": [], "products": []}247    if len(p) < 2:248        return out249    mots = p.split()250251    def colle(nom: str) -> int:252        """0 = commence par la saisie, 1 = un mot commence par, 2 = non."""253        n = texte.plier(nom)254        if n.startswith(p):255            return 0256        ns = n.split()257        if all(any(w.startswith(m) for w in ns) for m in mots):258            return 1259        return 2260    cc = _memo(cat, "catcount", 0, lambda: np.bincount(cat.p_cat, minlength=len(cats.CLES)))261    for k, lab in cats.LIBELLES.items():262        r = colle(lab)263        if r < 2 and cc[cats.INDEX_CLE[k]]:264            out["categories"].append((r, -int(cc[cats.INDEX_CLE[k]]), {265                "key": k, "label": lab, "slug": cats.SLUGS[k], "n": int(cc[cats.INDEX_CLE[k]]),266                "path": "/categorie/" + cats.SLUGS[k]}))267    for d in cat.sous:268        r = colle(d["label"])269        if r < 2:270            out["subcategories"].append((r, -d["n"], {271                "slug": d["slug"], "label": d["label"], "category": d["category"],272                "category_label": cats.LIBELLES[d["category"]], "n": d["n"],273                "path": f"/categorie/{cats.SLUGS[d['category']]}/{d['slug']}"}))274    for b in cat.boutiques:275        r = colle(b["name"])276        if r == 2 and b["id"].startswith(p.replace(" ", "")):277            r = 1278        if r < 2:279            out["stores"].append((r, -b["n"], {280                "id": b["id"], "name": b["name"], "city": b["city"] or None,281                "region": b["region"] or None, "n": b["n"], "logo": b["logo"],282                "path": "/boutiques/" + quote(b["id"])}))283    nv = _memo(cat, "villecount", 0, lambda: np.bincount(284        cat.b_ville[cat.b_ville >= 0], minlength=len(cat.villes)))285    for i, v in enumerate(cat.villes):286        r = colle(v)287        if r < 2:288            out["cities"].append((r, -int(nv[i]), {"name": v, "slug": texte.slug(v), "stores": int(nv[i]),289                                                   "path": "/ville/" + texte.slug(v)}))290    for rg in cat.regions:291        r = colle(rg)292        if r < 2:293            out["regions"].append((r, 0, {"name": rg, "slug": texte.slug(rg),294                                          "path": "/region/" + texte.slug(rg)}))295    for k in ("categories", "subcategories", "stores", "cities", "regions"):296        out[k] = [d for _, _, d in sorted(out[k], key=lambda x: (x[0], x[1]))[:limite]]297    # compléments du dernier mot (vocabulaire des titres)298    dernier = texte.racine(mots[-1])299    var, _ = cat.variantes(dernier, True)300    tete = " ".join(mots[:-1])301    out["terms"] = [(tete + " " + f).strip() for f, _ in sorted(var, key=lambda x: -cat.df.get(x[0], 0))302                    if len(f) > 2 and cat.df.get(f, 0) >= 5 and f != dernier][:limite]303    f = Filtres(cat, {"q": q})304    res = recherche.rechercher(cat, f, "pertinence", 1, limite, 1, prefixe_final=True)305    out["products"] = [{k: c[k] for k in ("uid", "title", "price", "img", "store_name", "path")}306                       for c in res["products"]]307    out["products_total"] = res["total"]308    if res.get("search", {}).get("corrections"):309        out["corrections"] = res["search"]["corrections"]310    return out311312313@app.get("/api/suggest")314def suggest(q: str = "", limit: int = 6):315    cat = catalogue()316    q = " ".join((q or "").split())[:80]317    limit = max(1, min(12, limit))318    return _json(_memo(cat, "suggest", (q.lower(), limit), lambda: _suggestions(cat, q, limit)),319                 max_age=300)320321322# =============================================================================323# Catégories324# =============================================================================325def arbre_categories(cat: Catalogue) -> list[dict]:326    def calc():327        cc = np.bincount(cat.p_cat, minlength=len(cats.CLES))328        out = []329        for i, k in enumerate(cats.CLES):330            if not cc[i]:331                continue332            idx = np.flatnonzero(cat.p_cat == i)333            bs = np.unique(cat.p_b[idx])334            # image d'illustration : produits récents de boutiques différentes335            imgs, vus = [], set()336            for j in idx[:400]:337                b = int(cat.p_b[j])338                if b not in vus:339                    vus.add(b); imgs.append(cat.img[int(j)])340                if len(imgs) == 4:341                    break342            out.append({343                "key": k, "label": cats.LIBELLES[k], "slug": cats.SLUGS[k],344                "path": "/categorie/" + cats.SLUGS[k], "n": int(cc[i]), "stores": int(len(bs)),345                "new": int(cat.p_nouveau[idx].sum()), "images": imgs,346                "subcategories": [{"slug": d["slug"], "label": d["label"], "n": d["n"],347                                   "stores": d["stores"],348                                   "path": f"/categorie/{cats.SLUGS[k]}/{d['slug']}"}349                                  for d in cat.sous if d["category"] == k]})350        out.sort(key=lambda d: (d["key"] == "autre", -d["n"]))351        return out352    return _memo(cat, "arbre", 0, calc)353354355@app.get("/api/categories")356def categories_():357    cat = catalogue()358    return _json({"categories": arbre_categories(cat), "total": cat.N,359                  "note": "Catégories recalculées à la lecture par mots entiers ; sous-catégories = "360                          "type de produit déclaré par les boutiques (≥ 25 produits, ≥ 2 boutiques)."},361                 max_age=600)362363364# =============================================================================365# Fiche produit366# =============================================================================367def _ligne(uid: str):368    con = public.connect_ro()369    try:370        return con.execute("SELECT * FROM products WHERE uid=?", (uid,)).fetchone()371    finally:372        con.close()373374375def _variantes(details: dict) -> tuple[list, list]:376    """Variantes et options normalisées (Shopify, WooCommerce, Wix, Square…)."""377    var, opts = [], []378    for v in (details.get("variants") or [])[:60]:379        if not isinstance(v, dict):380            continue381        nom = texte.titre_propre(str(v.get("title") or v.get("name") or ""))382        if nom.lower() in ("default title", "default", ""):383            nom = ""384        prix = v.get("price")385        try:386            prix = round(float(prix), 2) if prix not in (None, "") else None387        except (TypeError, ValueError):388            prix = None389        var.append({"name": nom or None, "price": prix,390                    "available": v.get("available") if isinstance(v.get("available"), bool) else None,391                    "sku": (str(v.get("sku")) if v.get("sku") else None),392                    "img": v.get("image") if isinstance(v.get("image"), str) else None})393    if len(var) == 1 and not var[0]["name"]:394        var = []395    for o in (details.get("options") or []) + (details.get("attributes") or []):396        if not isinstance(o, dict):397            continue398        nom = texte.titre_propre(str(o.get("name") or o.get("title") or ""))399        vals = o.get("values") or o.get("terms") or o.get("selections") or []400        vals = [texte.titre_propre(str(x)) for x in vals if x not in (None, "")][:40]401        if nom and vals and nom.lower() != "title":402            opts.append({"name": nom, "values": vals})403    return var, opts404405406def _faits(details: dict) -> list[dict]:407    """Détails secondaires présents dans la collecte (marque, poids, SKU…)."""408    out = []409    def ajoute(lab, v):410        if v not in (None, "", [], {}):411            out.append({"label": lab, "value": v})412    ajoute("Marque", details.get("brand"))413    g = details.get("weight_grams")414    if isinstance(g, (int, float)) and g > 0:415        ajoute("Poids", f"{g / 1000:.2f} kg".replace(".", ",") if g >= 1000 else f"{int(g)} g")416    ajoute("SKU", details.get("sku"))417    dims = details.get("dimensions")418    if isinstance(dims, dict):419        d = " × ".join(str(dims[k]) for k in ("length", "width", "height") if dims.get(k))420        ajoute("Dimensions", d)421    elif isinstance(dims, str):422        ajoute("Dimensions", dims)423    ajoute("Matériaux", details.get("materials"))424    r = details.get("rating") or details.get("average_rating")425    n = details.get("review_count") or details.get("reviews")426    if r:427        ajoute("Avis chez la boutique", f"{r} / 5" + (f" ({n} avis)" if n else ""))428    return out429430431def _semblables(cat: Catalogue, i: int, n: int = 8) -> list[dict]:432    """Produits semblables d'AUTRES boutiques : mots rares du titre en commun,433    même catégorie favorisée, un seul produit par boutique."""434    mots = [texte.racine(t) for t in cat.titre_plie[i].split()]435    mots = [t for t in dict.fromkeys(mots) if t not in texte.MOTS_VIDES and len(t) > 2436            and not t.isdigit() and 1 < cat.df.get(t, 0) < max(60, cat.N * 0.08)]437    mots.sort(key=lambda t: cat.df[t])438    mots = mots[:5]439    if not mots:440        return []441    s = np.zeros(cat.N, np.float32)442    lnN = math.log(cat.N + 1.0)443    for t in mots:444        idf = lnN - math.log(cat.df[t] + 1.0)445        a = cat._post(cat._titre_p, t)446        if a is not None:447            s[a] += np.float32(idf)448        a = cat._post(cat._autre_p, t)449        if a is not None:450            s[a] += np.float32(idf * 0.3)451    s_ = s452    s_[cat.p_b == cat.p_b[i]] = 0453    # même catégorie exigée : un nom propre (« Ariane ») ne suffit pas à rapprocher454    # une bague d'un manteau, d'une bière et d'un livre455    s_[cat.p_cat != cat.p_cat[i]] = 0456    if cat.p_sous[i] >= 0:457        s_[cat.p_sous == cat.p_sous[i]] *= 1.5458    k = min(200, cat.N - 1)459    top = np.argpartition(-s, k)[:k]460    top = top[np.argsort(-s[top], kind="stable")]461    out, vus = [], set()462    seuil = float(s[top[0]]) * 0.35 if len(top) else 0463    for j in top:464        if s[j] <= 0 or s[j] < seuil:465            break466        b = int(cat.p_b[j])467        if b in vus:468            continue469        vus.add(b)470        c = recherche.carte(cat, int(j))471        c["same_title"] = cat.titre_plie[int(j)] == cat.titre_plie[i]472        out.append(c)473        if len(out) == n:474            break475    return out476477478def resume_boutique(cat: Catalogue, b: dict) -> dict:479    return {"id": b["id"], "name": b["name"], "city": b["city"] or None, "city_slug": b["city_slug"] or None,480            "region": b["region"] or None, "region_slug": b["region_slug"] or None,481            "lat": b["lat"], "lng": b["lng"], "origin": b["origin"],482            "origin_label": recherche.libelle_origine(b),483            "category": b["category"], "category_label": cats.LIBELLES[b["category"]],484            "n": b["n"], "n_new": b["n_new"], "logo": b["logo"], "img": b["img"],485            "images": b["images"], "description": texte.resume(b["description"], 160) or None,486            "platform": b["platform"], "first_seen": b["first_seen"],487            "path": "/boutiques/" + quote(b["id"])}488489490def fiche_hors_regle(cat: Catalogue, uid: str, raison: str) -> dict | None:491    """Fiche d'un produit réel mais écarté des listes (sans photo, sans prix…) :492    atteignable par son adresse, `public: false`, jamais listée ni indexée."""493    r = _ligne(uid)494    if r is None or not r["active"] or r["store_id"] not in cat.b_index:495        return None496    b = cat.boutiques[cat.b_index[r["store_id"]]]497    titre = texte.titre_propre(r["title"])498    details = public._json(r["details"], {}) or {}499    tags = [t for t in (public._json(r["tags"], []) or []) if isinstance(t, str) and len(t) < 40][:20]500    k, _how = cats.categoriser(titre, r["product_type"] or "", " ".join(tags))501    imgs = [u for u in public._json(r["images"], []) if isinstance(u, str) and u.startswith("http")502            and not texte.photo_substitut(u)]503    cad = (r["currency"] or "CAD").upper() == "CAD"504    prix = r["price"] if (cad and r["price"] and public.PRIX_MIN <= r["price"] <= public.PRIX_MAX) else None505    desc = texte.description_propre(r["description"] or "")506    var, opts = _variantes(details)507    j = cat.b_index[r["store_id"]]508    return {509        "uid": uid, "title": titre, "price": prix,510        "price_max": (r["price_max"] if prix and r["price_max"] and r["price_max"] > prix else None),511        "compare_at_price": None, "discount_pct": None, "currency": "CAD",512        "available": None if r["available"] is None else bool(r["available"]),513        "img": imgs[0] if imgs else None, "n_img": len(imgs),514        "category": k, "category_label": cats.LIBELLES[k], "category_slug": cats.SLUGS[k],515        "subcategory": None, "subcategory_label": None,516        "store_id": b["id"], "store_name": b["name"], "city": b["city"] or None,517        "region": b["region"] or None, "origin": b["origin"],518        "first_seen": r["first_seen"], "days_listed": max(0, int((cat.genere - (r["first_seen"] or cat.genere)) // 86400)),519        "is_new": False, "variants_grouped": 1, "url": r["url"] or b["url"],520        "path": recherche.chemin_produit(uid, titre), "store_path": "/boutiques/" + quote(b["id"]),521        "images": imgs, "description": desc, "description_paragraphs": texte.paragraphes(desc),522        "summary": texte.resume(desc, 200),523        "vendor": texte.titre_propre(r["vendor"] or "") or None,524        "product_type": texte.titre_propre(r["product_type"] or "") or None, "tags": tags,525        "variants": var if prix else [], "options": opts, "facts": _faits(details),526        "last_seen": r["last_seen"], "source_updated_at": details.get("updated_at") or None,527        "public": False, "reason": raison, "reason_label": public.RAISONS.get(raison, raison),528        "store": {**resume_boutique(cat, b), "url": b["url"], "description": b["description"] or None,529                  "certifications": b["certifications"], "verification": b["verification"],530                  "position_precision": b["position_precision"]},531        "grouped": [],532        "same_store": [recherche.carte(cat, int(x)) for x in cat.b_produits[j][:8]],533        "similar": [], "generated_at": round(cat.genere, 1),534    }535536537def fiche(uid: str) -> dict | None:538    """Fiche complète d'un produit — même fonction pour l'API et pour539    l'amorçage de la page rendue par le serveur. `public: false` pour un540    produit réel écarté des listes (voir public.ATTEIGNABLES)."""541    cat = catalogue()542    i = cat.uid_index.get(uid)543    if i is None:544        raison = cat.hors_regle.get(uid)545        return fiche_hors_regle(cat, uid, raison) if raison else None546    r = _ligne(uid)547    if r is None:548        return None549    out = recherche.carte(cat, i)550    b = cat.boutiques[int(cat.p_b[i])]551    details = public._json(r["details"], {}) or {}552    imgs = [u for u in public._json(r["images"], []) if isinstance(u, str) and u.startswith("http")553            and not texte.photo_substitut(u)]554    desc = texte.description_propre(r["description"] or "")555    var, opts = _variantes(details)556    out.update({557        "images": imgs or [out["img"]],558        "description": desc, "description_paragraphs": texte.paragraphes(desc),559        "summary": texte.resume(desc, 200),560        "vendor": texte.titre_propre(r["vendor"] or "") or None,561        "product_type": texte.titre_propre(r["product_type"] or "") or None,562        "tags": [t for t in (public._json(r["tags"], []) or []) if isinstance(t, str) and len(t) < 40][:20],563        "variants": var, "options": opts, "facts": _faits(details),564        "last_seen": r["last_seen"],565        "source_updated_at": details.get("updated_at") or None,566        "public": True,567        "store": {**resume_boutique(cat, b), "url": b["url"], "description": b["description"] or None,568                  "certifications": b["certifications"], "verification": b["verification"],569                  "position_precision": b["position_precision"],570                  "stats": {"products": b["n"], "new": b["n_new"], "in_stock": b["n_in_stock"],571                            "price_min": b["price_min"], "price_median": b["price_median"],572                            "price_max": b["price_max"]}},573    })574    # déclinaisons regroupées (même nom, même boutique)575    autres = cat.groupe_de.get(uid) or []576    if autres:577        con = public.connect_ro()578        try:579            rows = con.execute(580                "SELECT uid, url, price, price_max, available, images FROM products WHERE uid IN (%s)"581                % ",".join("?" * len(autres[:40])), autres[:40]).fetchall()582        finally:583            con.close()584        out["grouped"] = [{"uid": x["uid"], "url": x["url"], "price": x["price"],585                           "available": None if x["available"] is None else bool(x["available"]),586                           "img": (public._json(x["images"], []) or [None])[0]} for x in rows]587    else:588        out["grouped"] = []589    # même boutique : produits de la même catégorie d'abord, hors celui-ci590    idx = cat.b_produits[int(cat.p_b[i])]591    idx = idx[idx != i]592    meme = idx[cat.p_cat[idx] == cat.p_cat[i]]593    choix = list(meme[:8]) + [j for j in idx[:16] if j not in set(meme[:8])]594    out["same_store"] = [recherche.carte(cat, int(j)) for j in choix[:8]]595    out["similar"] = _semblables(cat, i)596    out["generated_at"] = round(cat.genere, 1)597    return out598599600def etat_produit(uid: str) -> tuple[int, dict]:601    """Pourquoi un produit n'a pas de fiche : (statut HTTP, corps)."""602    cat = catalogue()603    rep = cat.regroupes.get(uid)604    if rep:605        j = cat.uid_index.get(rep)606        return 404, {"detail": "Produit regroupé sous un autre produit de même nom.",607                     "reason": "doublon_meme_boutique", "canonical_uid": rep,608                     "canonical_path": recherche.chemin_produit(rep, cat.titre[j]) if j is not None else None}609    r = _ligne(uid)610    if r is None:611        return 404, {"detail": "Produit inconnu."}612    if not r["active"]:613        return 410, {"detail": "Ce produit n'est plus offert par la boutique.", "reason": "retire",614                     "store_id": r["store_id"] if r["store_id"] in cat.b_index else None}615    return 404, {"detail": "Produit non publié.", "reason": "non_public",616                 "store_id": r["store_id"] if r["store_id"] in cat.b_index else None}617618619_UID = re.compile(r"^[0-9a-f]{20}$")620621622@app.get("/api/products")623def products_lot(ids: str = ""):624    """Lecture par lot (favoris gardés sur l'appareil) : jusqu'à 100 identifiants,625    séparés par des virgules. Rend les cartes des produits publics, dans l'ordre626    demandé, et dit ce que sont devenus les autres."""627    if not ids.strip():628        return _json({"detail": "Remplacé par /api/search (liste), /api/products?ids= (lot) et "629                                "/api/products/{uid} (fiche)."}, status=410, max_age=3600)630    demandes = list(dict.fromkeys(x.strip().lower() for x in ids.split(",") if x.strip()))631    if len(demandes) > 100:632        raise Erreur("ids : 100 identifiants au plus")633    cat = catalogue()634    cartes, autres, a_voir = [], [], []635    for u in demandes:636        i = cat.uid_index.get(u) if _UID.match(u) else None637        if i is not None:638            cartes.append(recherche.carte(cat, i))639        elif u in cat.regroupes:640            rep = cat.regroupes[u]641            c = recherche.carte(cat, cat.uid_index[rep])642            c["requested_uid"] = u643            cartes.append(c)644        elif u in cat.hors_regle:645            autres.append({"uid": u, "status": "unlisted", "reason": cat.hors_regle[u]})646        elif _UID.match(u):647            a_voir.append(u)648        else:649            autres.append({"uid": u, "status": "unknown"})650    if a_voir:651        con = public.connect_ro()652        try:653            connus = dict(con.execute("SELECT uid, active FROM products WHERE uid IN (%s)"654                                      % ",".join("?" * len(a_voir)), a_voir).fetchall())655        finally:656            con.close()657        for u in a_voir:658            autres.append({"uid": u, "status": "unknown" if u not in connus659                           else ("gone" if not connus[u] else "unlisted")})660    return _json({"total": len(cartes), "products": cartes, "unavailable": autres,661                  "generated_at": round(cat.genere, 1)}, max_age=60)662663664@app.get("/api/products/{uid}")665def get_product(uid: str):666    if not _UID.match(uid):667        raise HTTPException(404, "Produit inconnu.")668    cat = catalogue()669    v = _memo(cat, "fiche", uid, lambda: fiche(uid) or False)670    if not v:671        code, corps = etat_produit(uid)672        return _json(corps, status=code, max_age=60)673    return _json(v, max_age=120)674675676@app.get("/api/products/{uid}/pdf")677def product_pdf(uid: str):678    from . import fichepdf679    v = fiche(uid) if _UID.match(uid) else None680    if not v or not v.get("public"):681        raise HTTPException(404, "Produit inconnu ou non publié.")682    pdf = fichepdf.fiche_produit(v, BASE)683    nom = texte.slug(v["title"])[:60] or uid684    return Response(pdf, media_type="application/pdf", headers={685        "Content-Disposition": f'inline; filename="fabri-ka-{nom}.pdf"',686        "Cache-Control": "public, max-age=600"})687688689# =============================================================================690# Boutiques691# =============================================================================692def _sociaux(b: dict) -> list[dict]:693    out, vus = [], set()694    for u in b["socials_raw"] or []:695        if not isinstance(u, str) or not u.startswith("http"):696            continue697        bas = u.lower()698        if any(x.lower() in bas for x in public._SOCIAUX_REPERTOIRES):699            continue700        h = (urlsplit(u).hostname or "").replace("www.", "")701        reseau = next((n for d, n in (("facebook.com", "Facebook"), ("instagram.com", "Instagram"),702                                      ("tiktok.com", "TikTok"), ("youtube.com", "YouTube"),703                                      ("linkedin.com", "LinkedIn"), ("pinterest.", "Pinterest"),704                                      ("twitter.com", "X"), ("x.com", "X")) if d in h), None)705        chemin = urlsplit(u).path.strip("/")706        if not reseau or not chemin or reseau in vus:707            continue708        seg = chemin.split("/")709        # l'adresse du COMPTE : une publication, une vidéo ou un partage est ramené au compte710        if reseau in ("Facebook", "Instagram", "TikTok", "X", "Pinterest"):711            if seg[0].lower() in ("p", "reel", "reels", "share", "sharer", "sharer.php", "watch", "video",712                                  "videos", "photo", "photos", "posts", "events", "groups", "hashtag",713                                  "explore", "stories", "tr", "plugins", "dialog", "intent", "home",714                                  "login", "pin", "status"):715                continue716            if seg[0].lower() in ("pages", "people") and len(seg) >= 3:717                u = f"https://{h}/{seg[0]}/{seg[1]}/{seg[2]}"718            elif seg[0].lower() == "profile.php":719                pass720            else:721                u = f"https://{h}/{seg[0]}"722        vus.add(reseau)723        out.append({"network": reseau, "url": u})724    return out725726727def _livraison(b: dict) -> str | None:728    t = texte.description_propre(b.get("shipping_raw") or "", 700)729    # le champ est une page aplatie, souvent prise au milieu d'une phrase : on repart730    # de la première phrase entière731    if t and not (t[0].isupper() or t[0].isdigit()):732        m = re.search(r"[.!?]\s+(?=[A-ZÀ-Ý])", t)733        t = t[m.end():] if m else ""734    if len(t) < 40 or re.search(r"[{};]|max-width|!important", t):735        return None736    # le champ contient souvent le menu ou le pied de page de la boutique :737    # on ne le rend que s'il parle bien de livraison, sans bruit d'interface738    tete = texte.plier(t[:220])739    if not re.search(r"livraison|expedi|shipping|ramassage|cueillette|delivery", tete) or \740            re.search(r"langue|language|inscrivez|newsletter|infolettre|subscribe|panier|cart|"741                      r"soumettre|connexion|login|cookies|menu", tete):742        return None743    return texte.resume(t, 320)744745746def _distance_km(lat, lng, lats, lngs):747    r = 6371.0748    p1, p2 = np.radians(lat), np.radians(lats)749    dphi, dl = p2 - p1, np.radians(lngs - lng)750    a = np.sin(dphi / 2) ** 2 + np.cos(p1) * np.cos(p2) * np.sin(dl / 2) ** 2751    return 2 * r * np.arcsin(np.sqrt(a))752753754def fiche_boutique(store_id: str) -> dict | None:755    cat = catalogue()756    j = cat.b_index.get(store_id.lower())757    if j is None:758        a = cat.annuaire.get(store_id.lower())759        if a is None:760            return None761        return {**a, "catalogue": False, "public": False,762                "note": "Boutique répertoriée, sans catalogue suivi par Fabri-Ka.",763                "path": "/boutiques/" + quote(a["id"])}764    b = cat.boutiques[j]765    tel = texte.telephone(b["phone_raw"])766    out = {**resume_boutique(cat, b), "catalogue": True, "public": True,767           "url": b["url"], "description": b["description"] or None, "cover": b["cover"],768           "language": b["language"], "position_precision": b["position_precision"],769           "region_source": b["region_source"] or None, "postal_prefix": b["postal_prefix"],770           "contact": {"phone": tel, "email": texte.courriel(b["email_raw"]), "website": b["url"],771                       "socials": _sociaux(b)},772           "shipping": _livraison(b),773           "origin_evidence": b["origin_evidence"] or None, "origin_class": b["origin_class"],774           "verification": b["verification"], "verification_date": b["verification_date"],775           "certifications": b["certifications"], "listed_by": b["sources"],776           "categories": b["categories"],777           "stats": {"products": b["n"], "new": b["n_new"], "in_stock": b["n_in_stock"],778                     "price_min": b["price_min"], "price_median": b["price_median"],779                     "price_max": b["price_max"], "last_added": b["last_added"]},780           "freshness": {"last_sync": b["last_sync"], "last_ok": b["last_ok"],781                         "status": b["last_status"],782                         "hours_since_ok": (round((cat.genere - b["last_ok"]) / 3600, 1)783                                            if b["last_ok"] else None),784                         "cadence_hours": 6},785           "excluded": [{"reason": k, "label": public.RAISONS.get(k, k), "n": v}786                        for k, v in sorted((cat.exclus_par_boutique.get(b["id"]) or {}).items(),787                                           key=lambda x: -x[1])]}788    # voisines (distance) et semblables (même spécialité)789    voisines = []790    if b["lat"] is not None:791        d = _distance_km(b["lat"], b["lng"], cat.b_lat, cat.b_lng)792        d[j] = np.nan793        for k in np.argsort(d)[:60]:794            if np.isnan(d[k]) or len(voisines) == 8:795                break796            v = resume_boutique(cat, cat.boutiques[int(k)])797            v["distance_km"] = round(float(d[k]), 1)798            voisines.append(v)799    out["nearby"] = voisines800    meme = [k for k in np.flatnonzero(cat.b_cat == cat.b_cat[j]) if k != j]801    meme.sort(key=lambda k: (cat.boutiques[int(k)]["region"] != b["region"], -cat.boutiques[int(k)]["n"]))802    out["similar"] = [resume_boutique(cat, cat.boutiques[int(k)]) for k in meme[:8]]803    out["generated_at"] = round(cat.genere, 1)804    return out805806807TRIS_BOUTIQUES = ("name", "size", "new", "recent", "random")808POINTS_BOUTIQUES = ["store_id", "lat", "lng", "n", "name", "city", "region", "category", "img"]809810811def _point(b: dict) -> list:812    return [b["id"], b["lat"], b["lng"], b["n"], b["name"], b["city"] or None, b["region"] or None,813            b["category"], b["img"]]814815816def _rang_nom(cat: Catalogue, q: str) -> np.ndarray | None:817    """Rang de correspondance d'un texte avec chaque boutique (9 = aucune)."""818    brut = q.strip().lower()819    qp = texte.plier(q)820    if not qp:821        return None822    mots = qp.split()823    domaine = re.sub(r"^(https?://)?(www\.)?", "", brut).split("/")[0]824    colle = qp.replace(" ", "")825    rang = np.full(len(cat.boutiques), 9, np.int8)826    for k, b in enumerate(cat.boutiques):827        n = texte.plier(b["name"])828        ns = n.split()829        ident = b["id"].lower()830        if ident == domaine or n.startswith(qp):831            rang[k] = 0832        elif all(any(w.startswith(x) for w in ns) for x in mots):833            rang[k] = 1834        elif (len(domaine) > 3 and domaine in ident) or colle in ident.replace("-", "").replace(".", "") \835                or all(x in n for x in mots):836            rang[k] = 2837        elif all(x in texte.plier(b["description"] + " " + b["city"]) for x in mots):838            rang[k] = 3839    return rang840841842def liste_boutiques(cat: Catalogue, q="", region="", city="", category="", origin="",843                    platform="", size_min=None, size_max=None, new=False, sort="size",844                    page=1, page_size=24, points=False, seed=None, subcategory="",845                    facets=False) -> dict:846    if sort not in TRIS_BOUTIQUES:847        raise Erreur("sort : " + ", ".join(TRIS_BOUTIQUES))848    S = len(cat.boutiques)849    f = Filtres(cat, {"region": region, "city": city, "category": category, "origin": origin,850                      "platform": platform})851    m: dict[str, np.ndarray] = {}852    if f.region:853        m["region"] = np.isin(cat.b_region, f.region)854    if f.city:855        m["city"] = np.isin(cat.b_ville, f.city)856    if f.category:857        m["category"] = np.isin(cat.b_cat, [cats.INDEX_CLE[k] for k in f.category])858    if f.origin:859        m["origin"] = np.isin(cat.b_origine, f.origin)860    if f.platform:861        m["platform"] = np.array([b["platform"] in f.platform for b in cat.boutiques], bool)862    if subcategory:863        # boutiques qui ont au moins un produit de ce type (dans la catégorie donnée, s'il y en a une)864        fs = Filtres(cat, {"category": category, "subcategory": subcategory})865        n_sc = np.bincount(cat.p_b[np.isin(cat.p_sous, fs.subcategory)], minlength=S)866        m["subcategory"] = n_sc > 0867        m.pop("category", None)       # la catégorie sert ici à désigner le type, pas la spécialité868    if size_min is not None:869        m["size_min"] = cat.b_n >= size_min870    if size_max is not None:871        m["size_max"] = cat.b_n <= size_max872    if new:873        m["new"] = np.array([b["n_new"] > 0 for b in cat.boutiques], bool)874    rang = _rang_nom(cat, q)875    if rang is not None:876        m["q"] = rang < 9877878    def et(sauf=None):879        out = np.ones(S, bool)880        for k, v in m.items():881            if k != sauf:882                out &= v883        return out884    idx = np.flatnonzero(et())885    if sort == "name":886        pass                                   # déjà en ordre alphabétique887    elif sort == "size":888        idx = idx[np.argsort(-cat.b_n[idx], kind="stable")]889    elif sort == "new":890        idx = idx[np.argsort([-cat.boutiques[int(k)]["n_new"] for k in idx], kind="stable")]891    elif sort == "recent":892        idx = idx[np.argsort([-(cat.boutiques[int(k)]["first_seen"] or 0) for k in idx], kind="stable")]893    elif sort == "random":894        seed = int(time.time()) % 1_000_000 if seed is None else seed895        idx = idx[np.random.default_rng(seed).permutation(len(idx))]896    if rang is not None:897        idx = idx[np.argsort(rang[idx], kind="stable")]898    total = len(idx)899    page, page_size = max(1, page), max(1, min(100, page_size))900    out = {"total": int(total), "page": page, "page_size": page_size,901           "pages": max(1, math.ceil(total / page_size)), "sort": sort,902           "products_total": int(cat.b_n[idx].sum()),903           "stores": [resume_boutique(cat, cat.boutiques[int(k)])904                      for k in idx[(page - 1) * page_size: page * page_size]],905           "generated_at": round(cat.genere, 1)}906    if sort == "random":907        out["seed"] = seed908    if points:909        out["points_format"] = POINTS_BOUTIQUES910        out["points"] = [_point(b) for b in (cat.boutiques[int(k)] for k in idx) if b["lat"] is not None]911        out["unpositioned"] = int(total - len(out["points"]))912    if facets:913        # chaque dimension est comptée sans son propre filtre, comme pour les produits914        sel = et("category")915        cc = np.bincount(cat.b_cat[sel], minlength=len(cats.CLES))916        sel_r = et("region")917        rc = np.bincount(cat.b_region[sel_r & (cat.b_region >= 0)], minlength=len(cat.regions))918        sel_v = et("city")919        vc = np.bincount(cat.b_ville[sel_v & (cat.b_ville >= 0)], minlength=len(cat.villes))920        sel_o = et("origin")921        oc = np.bincount(cat.b_origine[sel_o], minlength=4)922        sel_p = et("platform")923        from collections import Counter924        pc = Counter(cat.boutiques[int(k)]["platform"] or "inconnue" for k in np.flatnonzero(sel_p))925        out["facets"] = {926            "categories": sorted(({"key": k, "label": cats.LIBELLES[k], "slug": cats.SLUGS[k], "n": int(cc[i])}927                                  for i, k in enumerate(cats.CLES) if cc[i]),928                                 key=lambda d: (d["key"] == "autre", -d["n"])),929            "regions": sorted(({"name": r, "slug": texte.slug(r), "n": int(rc[i])}930                               for i, r in enumerate(cat.regions) if rc[i]), key=lambda d: -d["n"]),931            "region_unknown": int((sel_r & (cat.b_region < 0)).sum()),932            "cities": [{"name": cat.villes[int(i)], "slug": texte.slug(cat.villes[int(i)]), "n": int(vc[i])}933                       for i in np.argsort(-vc)[:60] if vc[i]],934            "origins": [{"key": recherche.ORIGINE_LIBELLE[i], "label": recherche.ORIGINE_TEXTE[recherche.ORIGINE_LIBELLE[i]],935                         "n": int(oc[i])} for i in range(4) if oc[i]],936            "platforms": [{"platform": k, "n": v} for k, v in pc.most_common()],937            "new": int((et("new") & np.array([b["n_new"] > 0 for b in cat.boutiques], bool)).sum()),938            "total": int(total),939        }940    return out941942943def _annuaire(cat: Catalogue, q: str, region: str, city: str, category: str) -> list[dict]:944    """Fiches annuaire filtrées (nom ou domaine, région, ville, spécialité déclarée)."""945    brut = q.strip().lower()946    qp = texte.plier(q)947    rs = None948    if region:949        rs = cat.region_slug.get(texte.slug(region))950        if rs is None:951            raise Erreur(f"region : « {region} » inconnue")952    vs = texte.slug(city) if city else None953    ck = None954    if category:955        ck = cats.CLE_DU_SLUG.get(texte.slug(category)) or (category if category in cats.CATEGORIES else None)956        if ck is None:957            raise Erreur(f"category : « {category} » inconnue")958    ann = [a for a in cat.annuaire.values()959           if (not qp or qp in texte.plier(a["name"]) or (len(brut) > 3 and brut in a["id"]))960           and (not rs or a["region"] == rs)961           and (not vs or texte.slug(a["city"] or "") == vs)962           and (not ck or ck in a.get("categories", ()))]963    ann.sort(key=lambda a: texte.plier(a["name"]))964    return ann965966967@app.get("/api/boutiques")968def boutiques(request: Request, q: str = "", region: str = "", city: str = "", category: str = "",969              origin: str = "", platform: str = "", size_min: int | None = None,970              size_max: int | None = None, new: int = 0, sort: str = "size", page: int = 1,971              page_size: int = 24, points: int = 0, seed: int | None = None, directory: int = 0,972              directory_page: int = 1, directory_page_size: int = 200, subcategory: str = "",973              facets: int = 0, ids: str = ""):974    cat = catalogue()975    if ids.strip():976        # lecture par lot (boutiques gardées sur l'appareil) : dit aussi ce que sont devenues les autres977        demandes = list(dict.fromkeys(x.strip().lower() for x in ids.split(",") if x.strip()))978        if len(demandes) > 100:979            raise Erreur("ids : 100 identifiants au plus")980        trouvees, autres = [], []981        for x in demandes:982            j = cat.b_index.get(x)983            if j is not None:984                trouvees.append(resume_boutique(cat, cat.boutiques[j]))985            else:986                code, corps = etat_boutique(cat, x)987                autres.append({"id": x, "status": {410: "gone", 200: "directory"}.get(code, "unknown"),988                               **({"reason": corps["reason"]} if corps.get("reason") else {})})989        return _json({"total": len(trouvees), "stores": trouvees, "unavailable": autres,990                      "generated_at": round(cat.genere, 1)}, max_age=60)991    clef = (q.lower(), region, city, category, origin, platform, size_min, size_max, new, sort,992            page, page_size, points, seed, subcategory, facets)993    if sort == "random" and seed is None:994        out = liste_boutiques(cat, q, region, city, category, origin, platform, size_min, size_max,995                              bool(new), sort, page, page_size, bool(points), seed, subcategory,996                              bool(facets))997    else:998        out = _memo(cat, "boutiques", clef, lambda: liste_boutiques(999            cat, q, region, city, category, origin, platform, size_min, size_max, bool(new), sort,1000            page, page_size, bool(points), seed, subcategory, bool(facets)))1001    # fiches annuaire : répertoriées, sans catalogue suivi (jamais mêlées au total)1002    ann = _memo(cat, "annuaire", (q.lower(), region, city, category),1003                lambda: _annuaire(cat, q, region, city, category))1004    out = {**out, "directory_total": len(ann)}1005    if directory:1006        dps = max(1, min(500, directory_page_size))1007        dp = max(1, directory_page)1008        out.update({"directory_page": dp, "directory_page_size": dps,1009                    "directory_pages": max(1, math.ceil(len(ann) / dps)),1010                    "directory": [{"id": a["id"], "name": a["name"], "url": a["url"],1011                                   "region": a["region"] or None, "city": a["city"] or None,1012                                   "categories": list(a.get("categories", ())),1013                                   "path": "/boutiques/" + quote(a["id"])}1014                                  for a in ann[(dp - 1) * dps: dp * dps]]})1015    return _json(out, max_age=120)101610171018_RAISON_SORTIE = {"boutique_fermee": "La boutique ne répond plus : elle est présumée fermée.",1019                  "boutique_muette": "La boutique n'a pas pu être relevée depuis plusieurs jours.",1020                  "boutique_doublon": "La boutique est suivie sous un autre nom de domaine.",1021                  "boutique_origine_a_verifier": "L'origine québécoise de la boutique n'est pas établie.",1022                  "boutique_hors_mission": "La boutique ne vend pas de produits.",1023                  "boutique_hors_quebec": "La boutique n'est pas établie au Québec.",1024                  "sans_produit_public": "La boutique n'a plus de produit publiable."}102510261027def etat_boutique(cat: Catalogue, store_id: str) -> tuple[int, dict]:1028    """Ce qu'est devenue une boutique sans fiche publique : (statut, corps).1029    200 = fiche annuaire ; 410 = connue de la collecte, sortie du répertoire ;1030    404 = jamais vue."""1031    sid = store_id.lower()1032    if sid in cat.annuaire:1033        return 200, {}1034    if sid in cat.raison_boutique:1035        r = cat.raison_boutique[sid] or "sans_produit_public"1036        if r == "boutique_non_suivie":1037            return 404, {"detail": "Boutique inconnue."}1038        return 410, {"detail": "Cette boutique n'est plus au répertoire.", "gone": True, "id": sid,1039                     "reason": r, "reason_label": _RAISON_SORTIE.get(r, r),1040                     "name": cat.noms_sortis.get(sid)}1041    return 404, {"detail": "Boutique inconnue."}104210431044@app.get("/api/boutiques/names")1045def boutiques_noms():1046    """Tous les noms de boutiques publiques (autocomplétion hors ligne, iOS)."""1047    cat = catalogue()1048    return _json({"format": ["id", "name", "city", "region", "n"],1049                  "stores": [[b["id"], b["name"], b["city"] or None, b["region"] or None, b["n"]]1050                             for b in cat.boutiques]}, max_age=900)105110521053@app.get("/api/boutiques/{store_id}")1054def boutique(store_id: str, request: Request):1055    cat = catalogue()1056    v = _memo(cat, "boutique", store_id.lower(), lambda: fiche_boutique(store_id) or False)1057    if not v:1058        code, corps = etat_boutique(cat, store_id)1059        return _json(corps, status=code if code != 200 else 404, max_age=60)1060    qp = request.query_params1061    if v.get("catalogue") and recherche._flag(qp.get("products", "1")):1062        p = _params(request)1063        p["store"] = v["id"]1064        res = reponse_recherche(cat, p, qp.get("sort") or "",1065                                _entier(qp.get("page"), 1, 1, 100000, "page"),1066                                _entier(qp.get("page_size"), 24, 1, 60, "page_size"),1067                                0, False, True)1068        v = {**v, "products": {k: res[k] for k in ("total", "page", "page_size", "pages", "sort",1069                                                    "filters", "products")},1070             "facets": {k: res["facets"][k] for k in ("categories", "subcategories", "price",1071                                                      "in_stock", "new", "on_sale")}}1072    return _json(v, max_age=120)107310741075@app.get("/api/boutiques/{store_id}/pdf")1076def boutique_pdf(store_id: str):1077    from . import fichepdf1078    v = fiche_boutique(store_id)1079    if not v or not v.get("catalogue"):1080        raise HTTPException(404, "Boutique inconnue ou sans catalogue.")1081    cat = catalogue()1082    res = reponse_recherche(cat, {"store": v["id"]}, "", 1, 12, 0)1083    pdf = fichepdf.fiche_boutique(v, res["products"], BASE)1084    return Response(pdf, media_type="application/pdf", headers={1085        "Content-Disposition": f'inline; filename="fabri-ka-{texte.slug(v["name"])[:60]}.pdf"',1086        "Cache-Control": "public, max-age=600"})108710881089# =============================================================================1090# Régions, villes, carte de densité1091# =============================================================================1092def _lieu(cat: Catalogue, bs: np.ndarray, n_prod: int = 12) -> dict:1093    """Résumé d'un lot de boutiques : comptes, catégories fortes, nouveautés."""1094    S = len(cat.boutiques)1095    sm = np.zeros(S, bool); sm[bs] = True1096    sel = sm[cat.p_b]1097    idx = np.flatnonzero(sel)1098    cc = np.bincount(cat.p_cat[idx], minlength=len(cats.CLES))1099    tot = np.bincount(cat.p_cat, minlength=len(cats.CLES))1100    part_ici = cc / max(1, len(idx))1101    part_qc = tot / max(1, cat.N)1102    fortes = []1103    for i in np.argsort(-cc)[:8]:1104        if not cc[i] or cats.CLES[int(i)] == "autre":1105            continue1106        k = cats.CLES[int(i)]1107        fortes.append({"key": k, "label": cats.LIBELLES[k], "slug": cats.SLUGS[k], "n": int(cc[i]),1108                       "stores": int(len(np.unique(cat.p_b[idx][cat.p_cat[idx] == i]))),1109                       "share_pct": round(float(part_ici[i]) * 100, 1),1110                       "vs_quebec": round(float(part_ici[i] / part_qc[i]), 2) if part_qc[i] else None})1111    ordre = recherche.diversifier(cat, idx, 1)1112    lats = cat.b_lat[bs]; lngs = cat.b_lng[bs]1113    ok = ~np.isnan(lats)1114    return {"stores": int(len(bs)), "products": int(len(idx)),1115            "new": int(cat.p_nouveau[idx].sum()),1116            "categories": fortes,1117            "center": ({"lat": round(float(np.median(lats[ok])), 4), "lng": round(float(np.median(lngs[ok])), 4)}1118                       if ok.any() else None),1119            "bbox": ([round(float(lngs[ok].min()), 4), round(float(lats[ok].min()), 4),1120                      round(float(lngs[ok].max()), 4), round(float(lats[ok].max()), 4)] if ok.any() else None),1121            "latest": [recherche.carte(cat, int(i)) for i in ordre[:n_prod]]}112211231124def index_regions(cat: Catalogue) -> dict:1125    def calc():1126        out = []1127        for i, r in enumerate(cat.regions):1128            bs = np.flatnonzero(cat.b_region == i)1129            d = _lieu(cat, bs, 0) if len(bs) else {"stores": 0, "products": 0, "new": 0,1130                                                    "categories": [], "center": None, "bbox": None}1131            d.pop("latest", None)1132            villes = np.bincount(cat.b_ville[bs][cat.b_ville[bs] >= 0], minlength=len(cat.villes))1133            out.append({"name": r, "slug": texte.slug(r), "path": "/region/" + texte.slug(r), **d,1134                        "categories": d["categories"][:3],1135                        "cities": [{"name": cat.villes[int(v)], "slug": texte.slug(cat.villes[int(v)]),1136                                    "stores": int(villes[v])} for v in np.argsort(-villes)[:5] if villes[v]]})1137        sans = np.flatnonzero(cat.b_region < 0)1138        return {"regions": out, "total_regions": len(cat.regions),1139                "unknown": {"stores": int(len(sans)), "products": int(cat.b_n[sans].sum())}}1140    return _memo(cat, "regions", 0, calc)114111421143@app.get("/api/regions")1144def regions():1145    return _json(index_regions(catalogue()), max_age=600)114611471148def page_region(cat: Catalogue, slug: str) -> dict | None:1149    r = cat.region_slug.get(texte.slug(slug))1150    if r is None:1151        return None11521153    def calc():1154        i = cat.region_index[r]1155        bs = np.flatnonzero(cat.b_region == i)1156        d = _lieu(cat, bs) if len(bs) else {"stores": 0, "products": 0, "new": 0, "categories": [],1157                                            "center": None, "bbox": None, "latest": []}1158        villes = np.bincount(cat.b_ville[bs][cat.b_ville[bs] >= 0], minlength=len(cat.villes))1159        top = bs[np.argsort(-cat.b_n[bs], kind="stable")]1160        return {"name": r, "slug": texte.slug(r), "path": "/region/" + texte.slug(r), **d,1161                "cities": [{"name": cat.villes[int(v)], "slug": texte.slug(cat.villes[int(v)]),1162                            "stores": int(villes[v]), "path": "/ville/" + texte.slug(cat.villes[int(v)])}1163                           for v in np.argsort(-villes) if villes[v]],1164                "top_stores": [resume_boutique(cat, cat.boutiques[int(k)]) for k in top[:24]],1165                "points_format": POINTS_BOUTIQUES,1166                "points": [_point(b) for b in (cat.boutiques[int(k)] for k in bs) if b["lat"] is not None],1167                "search": {"region": texte.slug(r)}, "generated_at": round(cat.genere, 1)}1168    return _memo(cat, "region", r, calc)116911701171@app.get("/api/regions/{slug}")1172def region_detail(slug: str):1173    v = page_region(catalogue(), slug)1174    if v is None:1175        raise HTTPException(404, "Région inconnue.")1176    return _json(v, max_age=300)117711781179def index_villes(cat: Catalogue) -> list[dict]:1180    def calc():1181        out = []1182        for i, v in enumerate(cat.villes):1183            bs = np.flatnonzero(cat.b_ville == i)1184            reg = [cat.ville_region[v]] if v in cat.ville_region else []1185            lat = [cat.boutiques[int(k)]["lat"] for k in bs if cat.boutiques[int(k)]["lat"] is not None]1186            lng = [cat.boutiques[int(k)]["lng"] for k in bs if cat.boutiques[int(k)]["lng"] is not None]1187            out.append({"name": v, "slug": texte.slug(v), "path": "/ville/" + texte.slug(v),1188                        "region": max(set(reg), key=reg.count) if reg else None,1189                        "stores": int(len(bs)), "products": int(cat.b_n[bs].sum()),1190                        "lat": round(float(np.median(lat)), 4) if lat else None,1191                        "lng": round(float(np.median(lng)), 4) if lng else None})1192        return out1193    return _memo(cat, "villes", 0, calc)119411951196@app.get("/api/villes")1197def villes(region: str = "", min: int = 1, q: str = ""):1198    cat = catalogue()1199    vs = index_villes(cat)1200    if region:1201        r = cat.region_slug.get(texte.slug(region))1202        if r is None:1203            raise HTTPException(404, "Région inconnue.")1204        vs = [v for v in vs if v["region"] == r]1205    if q:1206        qp = texte.plier(q)1207        vs = [v for v in vs if qp in texte.plier(v["name"])]1208    vs = sorted((v for v in vs if v["stores"] >= min), key=lambda v: (-v["stores"], v["name"]))1209    return _json({"total": len(vs), "cities": vs,1210                  "note": "Ville = lieu rendu par le géocodage du code postal de la boutique "1211                          "(souvent un secteur ou un quartier), pas une adresse vérifiée."}, max_age=600)121212131214def page_ville(cat: Catalogue, slug: str) -> dict | None:1215    v = cat.ville_slug.get(texte.slug(slug))1216    if v is None:1217        return None12181219    def calc():1220        bs = np.flatnonzero(cat.b_ville == cat.ville_index[v])1221        base = next(x for x in index_villes(cat) if x["name"] == v)1222        d = _lieu(cat, bs)1223        top = bs[np.argsort(-cat.b_n[bs], kind="stable")]1224        proches = []1225        if base["lat"] is not None:1226            for o in index_villes(cat):1227                if o["name"] != v and o["lat"] is not None:1228                    dk = float(_distance_km(base["lat"], base["lng"], np.array([o["lat"]]), np.array([o["lng"]]))[0])1229                    if dk <= 40:1230                        proches.append({**{k: o[k] for k in ("name", "slug", "path", "stores")},1231                                        "distance_km": round(dk, 1)})1232            proches.sort(key=lambda x: x["distance_km"])1233        return {**base, **d,1234                "region_slug": texte.slug(base["region"]) if base["region"] else None,1235                "all_stores": [resume_boutique(cat, cat.boutiques[int(k)]) for k in top[:200]],1236                "points_format": POINTS_BOUTIQUES,1237                "points": [_point(b) for b in (cat.boutiques[int(k)] for k in bs) if b["lat"] is not None],1238                "nearby_cities": proches[:10],1239                "search": {"city": texte.slug(v)}, "generated_at": round(cat.genere, 1)}1240    return _memo(cat, "ville", v, calc)124112421243@app.get("/api/villes/{slug}")1244def ville_detail(slug: str):1245    v = page_ville(catalogue(), slug)1246    if v is None:1247        raise HTTPException(404, "Ville inconnue.")1248    return _json(v, max_age=300)124912501251@app.get("/api/lights")1252def lights(cell: float = 0.1, category: str = "", origin: str = ""):1253    """Carte de densité des boutiques : une cellule par carré de `cell` degrés.1254    Format : [lat, lng, boutiques, produits]."""1255    cat = catalogue()1256    if not (0.02 <= cell <= 2.0):1257        raise HTTPException(400, "cell : entre 0.02 et 2.0 degré")12581259    def calc():1260        m = ~np.isnan(cat.b_lat)1261        f = Filtres(cat, {"category": category, "origin": origin})1262        if f.category:1263            m &= np.isin(cat.b_cat, [cats.INDEX_CLE[k] for k in f.category])1264        if f.origin:1265            m &= np.isin(cat.b_origine, f.origin)1266        ks = np.flatnonzero(m)1267        la = np.floor(cat.b_lat[ks] / cell).astype(np.int64)1268        lo = np.floor(cat.b_lng[ks] / cell).astype(np.int64)1269        cle = la * 100000 + lo1270        u, inv = np.unique(cle, return_inverse=True)1271        nb = np.bincount(inv)1272        npd = np.bincount(inv, weights=cat.b_n[ks])1273        slat = np.bincount(inv, weights=cat.b_lat[ks]) / nb1274        slng = np.bincount(inv, weights=cat.b_lng[ks]) / nb1275        cells = [[round(float(slat[i]), 4), round(float(slng[i]), 4), int(nb[i]), int(npd[i])]1276                 for i in np.argsort(-nb)]1277        return {"cell": cell, "format": ["lat", "lng", "stores", "products"], "cells": cells,1278                "stores": int(len(ks)), "unpositioned": int(len(cat.boutiques) - int((~np.isnan(cat.b_lat)).sum())),1279                "max": int(nb.max()) if len(nb) else 0,1280                "note": "Positions au centre du secteur postal (trois premiers caractères du code "1281                        "postal) : plusieurs boutiques partagent le même point."}1282    return _json(_memo(cat, "lights", (cell, category, origin), calc), max_age=900)128312841285# =============================================================================1286# Découverte éditoriale (à partir des données seulement)1287# =============================================================================1288def _par_jour(cat: Catalogue, jours: int = 14) -> list[dict]:1289    """Nouveautés par jour civil (heure du serveur), du plus récent au plus ancien."""1290    out = []1291    minuit = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime(cat.genere)), "%Y-%m-%d"))1292    for k in range(jours):1293        d0 = minuit - k * 864001294        sel = cat.p_nouveau_large & (cat.p_vu >= d0) & (cat.p_vu < d0 + 86400)1295        n = int(sel.sum())1296        if n:1297            out.append({"day": time.strftime("%Y-%m-%d", time.localtime(d0 + 43200)), "products": n,1298                        "stores": int(len(np.unique(cat.p_b[sel])))})1299    return out130013011302def decouverte(cat: Catalogue) -> dict:1303    def calc():1304        semaine = np.flatnonzero(cat.p_nouveau & (cat.p_vu >= cat.genere - 7 * 86400))1305        nouveaux = recherche.diversifier(cat, semaine, 1)1306        recentes = sorted((b for b in cat.boutiques if b["first_seen"]),1307                          key=lambda b: -b["first_seen"])1308        # « récemment ajoutées » : arrivées après l'amorçage de la collecte1309        debut = min((b["first_seen"] for b in cat.boutiques if b["first_seen"]), default=0)1310        recentes = [b for b in recentes if b["first_seen"] > debut + 21 * 86400][:12]1311        return {1312            "new_this_week": {"total": int(len(semaine)),1313                              "stores": int(len(np.unique(cat.p_b[semaine]))) if len(semaine) else 0,1314                              "products": [recherche.carte(cat, int(i)) for i in nouveaux[:24]],1315                              "search": {"new": 1, "days_max": 7}},1316            "new_by_day": _par_jour(cat),1317            "new_stores": [resume_boutique(cat, b) for b in recentes],1318            "categories": [{k: c[k] for k in ("key", "label", "slug", "path", "n", "stores", "new", "images")}1319                           for c in arbre_categories(cat) if c["key"] != "autre"],1320            "regions": [{k: r[k] for k in ("name", "slug", "path", "stores", "products")}1321                        for r in index_regions(cat)["regions"]],1322            "totals": {"products": cat.N, "stores": len(cat.boutiques),1323                       "regions": int(len({b["region"] for b in cat.boutiques if b["region"]})),1324                       "cities": len(cat.villes)},1325            "generated_at": round(cat.genere, 1),1326        }1327    return _memo(cat, "decouverte", 0, calc)132813291330@app.get("/api/discover")1331def discover():1332    return _json(decouverte(catalogue()), max_age=300)133313341335def au_hasard(cat: Catalogue, kind: str, seed: int | None) -> dict:1336    if kind not in ("product", "store"):1337        raise Erreur("kind : product ou store")1338    if seed is None:1339        seed = random.SystemRandom().randrange(1, 1_000_000_000)1340    rng = np.random.default_rng(seed)1341    if kind == "store":1342        # tirage pondéré pour ne pas favoriser les très petites boutiques ni les géantes1343        j = int(rng.integers(0, len(cat.boutiques)))1344        b = cat.boutiques[j]1345        idx = cat.b_produits[j]1346        return {"kind": "store", "seed": seed, "path": f"/hasard/boutique/{seed}",1347                "store": resume_boutique(cat, b),1348                "products": [recherche.carte(cat, int(i)) for i in idx[:8]]}1349    # produit : on tire d'abord la boutique, puis le produit (sinon dix1350    # boutiques géantes sortiraient une fois sur trois)1351    j = int(rng.integers(0, len(cat.boutiques)))1352    idx = cat.b_produits[j]1353    i = int(idx[int(rng.integers(0, len(idx)))])1354    return {"kind": "product", "seed": seed, "path": f"/hasard/produit/{seed}",1355            "product": recherche.carte(cat, i),1356            "store": resume_boutique(cat, cat.boutiques[j])}135713581359@app.get("/api/random")1360def random_(kind: str = "product", seed: int | None = None):1361    out = au_hasard(catalogue(), kind, seed)1362    return _json(out, max_age=0 if seed is None else 300)136313641365# =============================================================================1366# Statistiques du répertoire, collecte1367# =============================================================================1368def statistiques(cat: Catalogue) -> dict:1369    def calc():1370        S = len(cat.boutiques)1371        cc = np.bincount(cat.p_cat, minlength=len(cats.CLES))1372        bcat = [len(np.unique(cat.p_b[cat.p_cat == i])) for i in range(len(cats.CLES))]1373        plat: dict = {}1374        for b in cat.boutiques:1375            d = plat.setdefault(b["platform"] or "inconnue", {"stores": 0, "products": 0})1376            d["stores"] += 1; d["products"] += b["n"]1377        ori = np.bincount(cat.b_origine, minlength=4)1378        orip = np.bincount(cat.b_origine[cat.p_b], minlength=4)1379        # évolution : produits vus pour la première fois, par semaine, hors amorçage1380        sem = ((cat.p_vu // (7 * 86400)) * 7 * 86400).astype(np.int64)1381        u, n = np.unique(sem, return_counts=True)1382        un, nn = np.unique(sem[cat.p_nouveau | (cat.p_vu > cat.genere - 90 * 86400)], return_counts=True)1383        fs = np.array([b["first_seen"] or 0 for b in cat.boutiques])1384        mois = Counter_mois(fs)1385        pr = cat.p_prix1386        taille = cat.b_n1387        return {1388            "totals": {"products": cat.N, "stores": S,1389                       "regions": int(len({b["region"] for b in cat.boutiques if b["region"]})),1390                       "cities": len(cat.villes), "categories": int((cc > 0).sum()),1391                       "subcategories": len(cat.sous),1392                       "in_stock": int((cat.p_dispo == 1).sum()),1393                       "out_of_stock": int((cat.p_dispo == 0).sum()),1394                       "stock_unknown": int((cat.p_dispo < 0).sum()),1395                       "on_sale": int((~np.isnan(cat.p_avant)).sum()),1396                       "new": int(cat.p_nouveau.sum()),1397                       "price_median": round(float(np.median(pr)), 2),1398                       "new_days": public.NOUVEAU_JOURS,1399                       "first_collect_at": float(min((b["first_seen"] for b in cat.boutiques if b["first_seen"]), default=0)) or None,1400                       "registry": cat.mesures["boutiques_registre"],1401                       "directory_only": cat.mesures["boutiques_annuaire"]},1402            "by_region": [{k: r[k] for k in ("name", "slug", "stores", "products", "new")}1403                          for r in sorted(index_regions(cat)["regions"], key=lambda r: -r["stores"])],1404            "region_unknown": index_regions(cat)["unknown"],1405            "by_category": sorted(({"key": k, "label": cats.LIBELLES[k], "slug": cats.SLUGS[k],1406                                    "products": int(cc[i]), "stores": int(bcat[i]),1407                                    "price_median": round(float(np.median(pr[cat.p_cat == i])), 2)}1408                                   for i, k in enumerate(cats.CLES) if cc[i]), key=lambda d: -d["products"]),1409            "by_platform": sorted(({"platform": k, **v} for k, v in plat.items()), key=lambda d: -d["stores"]),1410            "by_origin": [{"key": recherche.ORIGINE_LIBELLE[i], "label": recherche.ORIGINE_TEXTE[recherche.ORIGINE_LIBELLE[i]],1411                           "stores": int(ori[i]), "products": int(orip[i])} for i in range(4)],1412            "price_buckets": [{"min": a, "max": b, "n": int(((pr >= a) & (pr < (b if b is not None else 9e18))).sum())}1413                              for a, b in recherche.TRANCHES],1414            "store_sizes": [{"min": a, "max": b, "stores": int(((taille >= a) & (taille <= (b or 10**9))).sum()),1415                             "products": int(taille[(taille >= a) & (taille <= (b or 10**9))].sum())}1416                            for a, b in ((1, 9), (10, 49), (50, 199), (200, 999), (1000, 4999), (5000, None))],1417            "top_stores": [resume_boutique(cat, cat.boutiques[int(k)]) for k in np.argsort(-cat.b_n, kind="stable")[:15]],1418            "concentration": {"top10_share_pct": round(float(np.sort(taille)[-10:].sum() / cat.N * 100), 1),1419                              "top50_share_pct": round(float(np.sort(taille)[-50:].sum() / cat.N * 100), 1)},1420            "growth_weekly": [{"week": time.strftime("%Y-%m-%d", time.gmtime(int(w))), "new_products": int(c)}1421                              for w, c in zip(un, nn)],1422            "first_seen_weekly": [{"week": time.strftime("%Y-%m-%d", time.gmtime(int(w))), "products": int(c)}1423                                  for w, c in zip(u, n)],1424            "stores_by_month": mois,1425            "note": "La collecte a été amorcée en août 2026 : la première semaine de chaque boutique "1426                    "contient tout son catalogue. `growth_weekly` ne compte que les produits apparus "1427                    "ensuite.",1428            "generated_at": round(cat.genere, 1),1429        }1430    return _memo(cat, "stats", 0, calc)143114321433def Counter_mois(fs) -> list[dict]:1434    from collections import Counter1435    c = Counter(time.strftime("%Y-%m", time.gmtime(float(x))) for x in fs if x)1436    return [{"month": k, "stores": v} for k, v in sorted(c.items())]143714381439@app.get("/api/stats")1440def stats():1441    return _json(statistiques(catalogue()), max_age=600)144214431444_SOURCES = {"ts": 0.0, "data": None}1445_SOURCES_LOCK = threading.Lock()144614471448def etat_collecte(cat: Catalogue) -> dict:1449    """État de la collecte, lu dans la base de la v1 (cache 5 min)."""1450    if _SOURCES["data"] is not None and time.time() - _SOURCES["ts"] < 300:1451        return _SOURCES["data"]1452    with _SOURCES_LOCK:1453        if _SOURCES["data"] is not None and time.time() - _SOURCES["ts"] < 300:1454            return _SOURCES["data"]1455        con = public.connect_ro()1456        try:1457            now = time.time()1458            rows = con.execute(1459                "SELECT platform, COUNT(*), SUM(last_status='ok'), SUM(last_status='error'), "1460                "SUM(last_status='suspect'), SUM(COALESCE(presumed_closed,0)), MAX(last_sync) "1461                "FROM stores WHERE enabled=1 AND platform<>'' AND catalog_endpoint<>'' GROUP BY platform").fetchall()1462            jour = con.execute(1463                "SELECT COUNT(*), SUM(status='ok'), SUM(status='error'), SUM(status='suspect'), "1464                "SUM(added), SUM(removed), MIN(ts), MAX(ts) FROM sync_log WHERE ts>?",1465                (now - 86400,)).fetchone()1466        finally:1467            con.close()1468        pub: dict = {}1469        for b in cat.boutiques:1470            d = pub.setdefault(b["platform"], [0, 0])1471            d[0] += 1; d[1] += b["n"]1472        plats = []1473        for r in rows:1474            plats.append({"platform": r[0], "followed": r[1], "ok": r[2] or 0, "failing": r[3] or 0,1475                          "suspect": r[4] or 0, "presumed_closed": r[5] or 0, "last_sync": r[6],1476                          "public_stores": pub.get(r[0], [0, 0])[0],1477                          "public_products": pub.get(r[0], [0, 0])[1]})1478        plats.sort(key=lambda d: -d["followed"])1479        data = {"platforms": plats,1480                "followed": sum(p["followed"] for p in plats),1481                "failing": sum(p["failing"] for p in plats),1482                "cadence_hours": 6,1483                "last_24h": {"syncs": jour[0], "ok": jour[1] or 0, "errors": jour[2] or 0,1484                             "suspect": jour[3] or 0, "products_added": jour[4] or 0,1485                             "products_removed": jour[5] or 0, "from": jour[6], "to": jour[7]},1486                "last_collect_at": cat.derniere_passe,1487                "method": "Catalogues publics des boutiques, lus par leur plateforme (Shopify "1488                          "/products.json, API Store de WooCommerce, vitrines Wix, Square, "1489                          "Squarespace…), toutes les six heures. Aucune donnée derrière une "1490                          "authentification. Chaque produit renvoie à la boutique d'origine.",1491                "listed_by": sorted({s for b in cat.boutiques for s in b["sources"]}),1492                "generated_at": round(now, 1)}1493        _SOURCES.update(ts=time.time(), data=data)1494        return data149514961497@app.get("/api/sources")1498def sources():1499    return _json(etat_collecte(catalogue()), max_age=300)150015011502@app.get("/api/stats/report.pdf")1503def rapport_pdf():1504    from . import fichepdf1505    cat = catalogue()1506    pdf = fichepdf.rapport(statistiques(cat), etat_collecte(cat), public.REGLES, BASE)1507    return Response(pdf, media_type="application/pdf", headers={1508        "Content-Disposition": f'inline; filename="fabri-ka-repertoire-{time.strftime("%Y-%m-%d")}.pdf"',1509        "Cache-Control": "public, max-age=3600"})151015111512# =============================================================================1513# /api/img — miniatures WebP en cache1514# =============================================================================1515_IMG_WIDTHS = (96, 160, 320, 480, 640, 800, 1280, 1920)1516_IMG_CACHE = VAR / "imgcache"1517_IMG_MAX = 15 * 1024 * 1024151815191520def _hotes_images(cat: Catalogue) -> set[str]:1521    def calc():1522        hs: set[str] = set()1523        for u in cat.img:1524            h = urlsplit(u).hostname1525            if h:1526                hs.add(h.lower())1527        for b in cat.boutiques:1528            for u in (b["logo"], b["cover"]):1529                if u:1530                    h = urlsplit(u).hostname1531                    if h:1532                        hs.add(h.lower())1533            hs.add(b["id"]); hs.add("www." + b["id"])1534        return hs1535    return _memo(cat, "hotes", 0, calc)153615371538def _hote_permis(cat: Catalogue, h: str) -> bool:1539    hs = _hotes_images(cat)1540    if h in hs:1541        return True1542    if re.fullmatch(r"[\d.:\[\]a-f]+|localhost", h) or "." not in h:1543        return False1544    base = "." + ".".join(h.split(".")[-2:])1545    return any(x.endswith(base) for x in hs)154615471548def chemin_miniature(u: str, w: int, trim: bool) -> Path:1549    nom = hashlib.sha1(f"{w}|{int(trim)}|{u}".encode()).hexdigest()1550    return _IMG_CACHE / nom[:2] / (nom + ".webp")155115521553def _rogner(im):1554    """Retire les marges unies (fond blanc ou transparent) autour du sujet."""1555    from PIL import Image, ImageChops1556    try:1557        rgb = im.convert("RGB")1558        fond = Image.new("RGB", rgb.size, rgb.getpixel((0, 0)))1559        diff = ImageChops.difference(rgb, fond).convert("L").point(lambda p: 255 if p > 14 else 0)1560        boite = diff.getbbox()1561        if boite and (boite[2] - boite[0]) > im.width * 0.2 and (boite[3] - boite[1]) > im.height * 0.2:1562            marge = int(max(im.size) * 0.02)1563            boite = (max(0, boite[0] - marge), max(0, boite[1] - marge),1564                     min(im.width, boite[2] + marge), min(im.height, boite[3] + marge))1565            return im.crop(boite)1566    except Exception:  # noqa: BLE0011567        pass1568    return im156915701571def miniature(cat: Catalogue, u: str, w: int, trim: bool = False) -> bytes:1572    import requests1573    from PIL import Image1574    parts = urlsplit(u)1575    host = (parts.hostname or "").lower()1576    if parts.scheme not in ("http", "https") or not host:1577        raise HTTPException(400, "URL d'image invalide")1578    if not _hote_permis(cat, host):1579        raise HTTPException(403, "Hôte d'image non autorisé")1580    chemin = chemin_miniature(u, w, trim)1581    if chemin.is_file():1582        return chemin.read_bytes()1583    try:1584        r = requests.get(u.replace(" ", "%20"), timeout=12, stream=True, allow_redirects=False, headers={1585            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "1586                          "(KHTML, like Gecko) Chrome/126 Safari/537.36",1587            "Accept": "image/avif,image/webp,image/*,*/*;q=0.8",1588            "Referer": f"{parts.scheme}://{host}/"})1589        if r.status_code in (301, 302, 307, 308):1590            loc = r.headers.get("Location") or ""1591            lh = (urlsplit(loc).hostname or "").lower()1592            if loc.startswith("http") and _hote_permis(cat, lh):1593                r = requests.get(loc, timeout=12, stream=True, allow_redirects=False,1594                                 headers={"User-Agent": "Mozilla/5.0", "Accept": "image/*"})1595        if r.status_code != 200:1596            raise HTTPException(404, f"Image indisponible chez la boutique (HTTP {r.status_code})")1597        brut = r.raw.read(_IMG_MAX + 1, decode_content=True)1598        if len(brut) > _IMG_MAX:1599            raise HTTPException(413, "Image trop lourde")1600        im = Image.open(io.BytesIO(brut))1601        im.load()1602    except HTTPException:1603        raise1604    except Exception:  # noqa: BLE0011605        raise HTTPException(404, "Image illisible ou indisponible")1606    if getattr(im, "n_frames", 1) > 1:1607        im.seek(0)1608    if im.mode not in ("RGB", "RGBA"):1609        im = im.convert("RGBA" if "A" in im.getbands() or "transparency" in im.info else "RGB")1610    if trim:1611        im = _rogner(im)1612    if im.width > w:1613        im = im.resize((w, max(1, round(im.height * w / im.width))), Image.LANCZOS)1614    tampon = io.BytesIO()1615    im.save(tampon, "WEBP", quality=80, method=4)1616    data = tampon.getvalue()1617    try:1618        chemin.parent.mkdir(parents=True, exist_ok=True)1619        tmp = chemin.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp")1620        tmp.write_bytes(data)1621        os.replace(tmp, chemin)1622    except OSError:1623        pass1624    return data162516261627@app.get("/api/img")1628def img(u: str, w: int = 480, trim: int = 0):1629    """Miniature WebP d'une photo de produit ou d'un logo de boutique, ramenée à1630    `w` pixels de large, gardée en cache sur disque. `trim=1` retire les marges1631    unies. Seuls les hôtes d'images du catalogue sont acceptés."""1632    if w not in _IMG_WIDTHS:1633        raise HTTPException(400, "w : " + ", ".join(str(x) for x in _IMG_WIDTHS))1634    return Response(miniature(catalogue(), u, w, bool(trim)), media_type="image/webp",1635                    headers={"Cache-Control": "public, max-age=2592000, immutable"})163616371638# =============================================================================1639# Routes retirées avec la v1 (comptes, favoris serveur, formats v1)1640# =============================================================================1641_RETIREES = {1642    "/api/auth": "Fabri-Ka n'a plus de compte : rien à connecter.",1643    "/api/kaid": "La personnalisation par compte est retirée ; les préférences restent sur l'appareil.",1644    "/api/favorites": "Les favoris restent sur l'appareil.",1645    "/api/profile": "Fabri-Ka n'a plus de profil.",1646    "/api/sync": "La collecte ne se déclenche plus par l'API.",1647    "/api/stores": "Remplacé par /api/boutiques.",1648    "/api/stats/extended": "Remplacé par /api/stats.",1649    "/api/stats/dashboard": "Remplacé par /api/stats.",1650    "/api/stats/report": "Remplacé par /api/stats/report.pdf.",1651    "/api/stats/catalog": "Remplacé par /api/stats.",1652    "/api/report.pdf": "Remplacé par /api/stats/report.pdf.",1653}165416551656@app.api_route("/api/{reste:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"],1657               include_in_schema=False)1658def api_inconnue(reste: str):1659    chemin = "/api/" + reste1660    for prefixe, msg in _RETIREES.items():1661        if chemin == prefixe or chemin.startswith(prefixe + "/"):1662            return _json({"detail": msg, "gone": True}, status=410, max_age=3600)1663    return _json({"detail": "Route inconnue."}, status=404, max_age=60)166416651666# =============================================================================1667# Démarrage : catalogue en arrière-plan, préchauffage, reconstruction périodique1668# =============================================================================1669def _prechauffer(cat: Catalogue) -> None:1670    t0 = time.time()1671    try:1672        reponse_recherche(cat, {}, "", 1, 24, None, True, True)1673        arbre_categories(cat); index_regions(cat); index_villes(cat)1674        decouverte(cat); statistiques(cat); etat_collecte(cat); _hotes_images(cat)1675        for k in cats.CLES:1676            if k != "autre":1677                reponse_recherche(cat, {"category": k}, "", 1, 24, None, False, True)1678        for r in cat.regions:1679            page_region(cat, r)1680    except Exception as exc:  # noqa: BLE0011681        print(f"[fabri-ka v2] préchauffage : {exc}", flush=True)1682    cat.mesures["prechauffage_s"] = round(time.time() - t0, 2)1683    threading.Thread(target=_prechauffer_miniatures, args=(cat,), daemon=True, name="miniatures").start()168416851686_MINI_LOCK = threading.Lock()168716881689def _prechauffer_miniatures(cat: Catalogue) -> None:1690    """Fabrique d'avance les miniatures du premier affichage des pages les plus1691    vues (accueil, /produits, chaque catégorie, /boutiques) : le premier visiteur1692    ne paie pas leur génération. Hors du chemin des requêtes, une à la fois,1693    plafonné ; les miniatures déjà en cache ne coûtent rien."""1694    if not _MINI_LOCK.acquire(blocking=False):1695        return1696    try:1697        cibles: list[tuple[str, int]] = []1698        d = decouverte(cat)["new_this_week"]["products"]1699        if d:1700            cibles += [(d[0]["img"], 640), (d[0]["img"], 480)]1701        tete = reponse_recherche(cat, {}, "", 1, 24, None, False, True)["products"]1702        for c in tete[:4]:1703            cibles.append((c["img"], 480))1704        if tete:   # la première fiche qu'on ouvre depuis la liste1705            cibles += [(tete[0]["img"], 800), (tete[0]["img"], 480)]1706        for k in cats.CLES:1707            if k != "autre":1708                for c in reponse_recherche(cat, {"category": k}, "", 1, 24, None, False, True)["products"][:2]:1709                    cibles.append((c["img"], 480))1710        for b in liste_boutiques(cat, page_size=24)["stores"][:3]:1711            cibles += [(u, 320) for u in b["images"]]1712        fait = 01713        for u, w in dict.fromkeys(cibles):1714            if fait >= 80:1715                break1716            if not u or chemin_miniature(u, w, False).is_file():1717                continue1718            try:1719                miniature(cat, u, w)1720                fait += 11721            except Exception:  # noqa: BLE0011722                pass1723            time.sleep(0.1)1724        cat.mesures["miniatures_prechauffees"] = fait1725    except Exception as exc:  # noqa: BLE0011726        print(f"[fabri-ka v2] miniatures : {exc}", flush=True)1727    finally:1728        _MINI_LOCK.release()172917301731def _demarrer() -> None:1732    def premier():1733        try:1734            cat = catalogue()1735            _prechauffer(cat)1736            _ETAT["pret"] = True1737            print(f"[fabri-ka v2] catalogue prêt : {cat.N} produits, {len(cat.boutiques)} boutiques "1738                  f"({cat.mesures['construction_s']} s + préchauffage {cat.mesures.get('prechauffage_s')} s)",1739                  flush=True)1740        except Exception as exc:  # noqa: BLE0011741            _ETAT["erreur"] = f"{type(exc).__name__} : {exc}"[:300]1742            print(f"[fabri-ka v2] catalogue : {_ETAT['erreur']}", flush=True)1743            return17441745        def boucle():1746            while True:1747                time.sleep(public.RAFRAICHIR_S)1748                try:1749                    public.reconstruire(_prechauffer)1750                except Exception as exc:  # noqa: BLE0011751                    print(f"[fabri-ka v2] reconstruction : {exc}", flush=True)1752        threading.Thread(target=boucle, daemon=True, name="catalogue").start()1753    threading.Thread(target=premier, daemon=True, name="amorce").start()175417551756@app.on_event("startup")1757def _startup():1758    import sys1759    # la reconstruction du catalogue tourne dans un fil d'arrière-plan : un1760    # intervalle de bascule court garde les requêtes réactives pendant ce temps1761    sys.setswitchinterval(0.001)1762    _demarrer()176317641765# -- pages rendues par le serveur (après toutes les routes /api) -------------------1766from . import seo  # noqa: E40217671768seo.monter(app)1769
Files main
Menu

Theme