SPB Git

Repository Public

directory.py 15.7 KB 388 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/directory.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-11-2513# Last Modified    : 2026-11-2514#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# directory.py : annuaire des agences et des bannières de courtage.91#92# Trois listes prêtes à afficher :93#   - agencies   : les ~690 agences titulaires d'un permis OACIQ94#                  (data/bannieres.json), chacune avec son inventaire actif sur95#                  Immo-Ka, son prix médian, ses villes et son nombre de courtiers ;96#   - franchises : les bannières (RE/MAX, Royal LePage, Sutton, Via Capitale…)97#                  qui regroupent ces agences ;98#   - platforms  : les sources qui ne sont pas des agences (vente sans99#                  courtier, portails, petites annonces).100#101# L'inventaire d'une agence est rattaché par le champ `agency` des inscriptions102# (bureau inscripteur) ; à défaut, par la source dédiée qui la couvre. Une103# agence sans inventaire en ligne reste listée (registre officiel).104# Aucune note (étoiles) n'est disponible pour les agences : le champ `rating`105# est toujours nul — on n'invente pas de note.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import json110import re111import statistics112import threading113import time114import unicodedata115from pathlib import Path116117from . import db, public, villes118from .public import PRICE_MAX, PRICE_MIN, PUBLIC119120ROOT = Path(__file__).resolve().parent.parent121SOURCES_PATH = ROOT / "data" / "sources.json"122BANNIERES_PATH = ROOT / "data" / "bannieres.json"123124_TTL = 600  # secondes125_CACHE: dict = {"ts": 0.0, "data": None}126_LOCK = threading.Lock()127128# bannières de courtage : (nom affiché, motif sur le nom d'agence, sources du flux)129FRANCHISES = [130    ("RE/MAX", r"^re ?max\b", lambda s: s == "remax_quebec" or s.startswith("remax_ag_")),131    ("Royal LePage", r"^royal lepage\b", lambda s: s == "royal_lepage"),132    ("Groupe Sutton", r"^(groupe )?sutton\b", lambda s: s == "sutton"),133    ("Via Capitale", r"^via capitale\b", lambda s: s == "via_capitale" or s.startswith("via_ag_")),134    ("Century 21", r"^century 21\b", lambda s: s == "century21" or s.startswith("c21_ag_")),135    ("Keller Williams", r"^(keller williams|kw)\b", lambda s: s.startswith("kw_")),136    ("Proprio Direct", r"^proprio direct\b", lambda s: s == "proprio_direct"),137    ("eXp", r"^exp\b", lambda s: s == "exp_ag_qc"),138    ("Engel & Völkers", r"^engel\b", lambda s: s == "engel_volkers"),139    ("Sotheby's International Realty", r"^sotheby", lambda s: s == "sothebys_quebec"),140    ("Coldwell Banker", r"^coldwell banker\b", lambda s: s == "coldwell_banker"),141    ("Berkshire Hathaway HomeServices", r"^(berkshire hathaway|bhhs)\b", lambda s: s == "bhhs_ag_qc"),142    ("Vendirect", r"^vendirect\b", lambda s: s == "vendirect"),143]144# sources qui ne sont pas des agences de courtage145PLATFORM_TYPES = {"fsbo", "portail", "petites annonces", "agrégateur",146                  "répertoire", "chambre", "annuaire"}147PLATFORM_IDS = {"kijiji", "lespac", "fb_marketplace", "duproprio"}148# flux qui mélangent l'inventaire de nombreuses agences : jamais attribués en bloc149FEEDS = {"remax_quebec", "royal_lepage", "sutton", "via_capitale", "c21_ag_quebec",150         "proprio_direct", "realtor_ag_ca", "cio_ag_outaouais", "vendre_ag_ca",151         "logis_ag_quebec", "si_ag_ciemcq", "domicilia"}152153_STOP = re.compile(r"\b(inc|ltee|ltd|enr|agence immobiliere|agence|immobilier|"154                   r"immobiliere|courtier immobilier|real estate|realty|s e n c|senc)\b")155156157def _key(s: str) -> str:158    s = unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode().lower()159    s = _STOP.sub(" ", re.sub(r"[^a-z0-9]+", " ", s))160    return re.sub(r"\s+", " ", s).strip()161162163def _plain(s: str) -> str:164    s = unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode().lower()165    return re.sub(r"[^a-z0-9]+", " ", s).strip()166167168def franchise_of_name(name: str) -> str | None:169    p = _plain(name)170    for label, pattern, _ in FRANCHISES:171        if re.search(pattern, p):172            return label173    return None174175176def franchise_of_source(source: str) -> str | None:177    for label, _, match in FRANCHISES:178        if match(source):179            return label180    return None181182183def _nice(name: str) -> str:184    """« RE/MAX DU CARTIER INC. » → « RE/MAX du Cartier inc. » (registre en capitales)."""185    if name != name.upper():186        return name187    small = {"de", "du", "des", "la", "le", "les", "et", "d", "l", "inc.", "inc",188             "ltée", "enr.", "au", "aux", "sur", "en"}189    keep = {"RE/MAX", "KW", "EXP", "BHHS", "M", "MW", "PGL", "PM", "P.M."}190    out = []191    for i, w in enumerate(name.split()):192        if w in keep:193            out.append("eXp" if w == "EXP" else w)194        elif i and w.lower() in small:195            out.append(w.lower())196        else:197            out.append("-".join(p[:1].upper() + p[1:].lower() for p in w.split("-")))198    return " ".join(out)199200201class _Inv:202    """Inventaire agrégé d'un groupe d'inscriptions."""203    __slots__ = ("n", "prices", "cities", "last", "sources")204205    def __init__(self) -> None:206        self.n = 0207        self.prices: list[float] = []208        self.cities: dict[str, int] = {}209        self.last = 0.0210        self.sources: set[str] = set()211212    def add(self, r) -> None:213        self.n += 1214        if r["price"] is not None and PRICE_MIN <= r["price"] <= PRICE_MAX:215            self.prices.append(r["price"])216        ville = villes.label(r["city"])217        if ville:218            self.cities[ville] = self.cities.get(ville, 0) + 1219        if r["updated_at"] and r["updated_at"] > self.last:220            self.last = r["updated_at"]221        self.sources.add(r["source"])222223    def out(self) -> dict:224        top = sorted(self.cities.items(), key=lambda kv: -kv[1])225        return {226            "active_listings": self.n,227            "price_median": round(statistics.median(self.prices)) if self.prices else None,228            "price_min": round(min(self.prices)) if self.prices else None,229            "cities": [c for c, _ in top[:6]],230            "cities_total": len(top),231            "updated_at": self.last or None,232        }233234235_EMPTY = {"active_listings": 0, "price_median": None, "price_min": None,236          "cities": [], "cities_total": 0, "updated_at": None}237238239def _build() -> dict:240    registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]241    reg_by_id = {s["id"]: s for s in registry}242    doc = json.loads(BANNIERES_PATH.read_text(encoding="utf-8"))243244    by_label: dict[str, _Inv] = {}245    by_source: dict[str, _Inv] = {}246    by_franchise: dict[str, _Inv] = {}247    agencies_per_source: dict[str, set] = {}248    total = 0249    con = db.connect()250    try:251        for r in con.execute(252                f"""SELECT source, COALESCE(agency,'') agency, city, price, updated_at253                    FROM listings WHERE {PUBLIC}"""):254            total += 1255            by_source.setdefault(r["source"], _Inv()).add(r)256            if r["agency"]:257                by_label.setdefault(_key(r["agency"]), _Inv()).add(r)258                agencies_per_source.setdefault(r["source"], set()).add(r["agency"])259            fr = franchise_of_source(r["source"]) or franchise_of_name(r["agency"])260            if fr:261                by_franchise.setdefault(fr, _Inv()).add(r)262        last_sync = {r["source"]: r["ts"] for r in con.execute(263            "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 AND found>0"264            " GROUP BY source")}265    finally:266        con.close()267268    def dedicated(sid: str) -> bool:269        return (sid in by_source and sid not in FEEDS and sid not in PLATFORM_IDS270                and len(agencies_per_source.get(sid, ())) <= 2)271272    agencies = []273    independents = 0          # « Courtiers à leur compte (sans bannière) »274    for b in doc.get("bannieres", []):275        if _plain(b["name"]).startswith("courtiers a leur compte"):276            # entrée du registre qui regroupe les courtiers SANS agence : ce277            # n'est pas une agence ; ses courtiers sont comptés à part278            independents += b.get("brokers_n") or 0279            continue280        covered = re.sub(r"\s*\(.*$", "", b.get("covered_by") or "").strip() or None281        inv = by_label.get(_key(b["name"]))282        matched = "agence" if inv else None283        if inv is None and covered and dedicated(covered):284            inv, matched = by_source[covered], "source"285        src = reg_by_id.get(covered or "", {})286        agencies.append({287            "id": b["id"],288            "name": _nice(b["name"]),289            "franchise": franchise_of_name(b["name"]),290            "oaciq_id": b.get("oaciq_id"),291            "regions": [public.region_name(x) or x for x in (b.get("regions") or [])],292            "brokers": b.get("brokers_n") or 0,293            "url": b.get("site") or (src.get("url") if matched == "source" else None),294            "source": covered,295            "connected": bool(covered),296            "matched_by": matched,297            **(inv.out() if inv else _EMPTY),298            "rating": None, "reviews": None,299            "last_sync": last_sync.get(covered) if covered else None,300        })301    agencies.sort(key=lambda a: (-a["active_listings"], -a["brokers"], a["name"].lower()))302303    franchises = []304    for label, _, _ in FRANCHISES:305        members = [a for a in agencies if a["franchise"] == label]306        inv = by_franchise.get(label)307        if not members and not inv:308            continue309        regs: dict[str, int] = {}310        for a in members:311            for rg in a["regions"]:312                regs[rg] = regs.get(rg, 0) + 1313        franchises.append({314            "name": label,315            "agencies": len(members),316            "brokers": sum(a["brokers"] for a in members),317            "regions": [k for k, _ in sorted(regs.items(), key=lambda kv: -kv[1])],318            **(inv.out() if inv else _EMPTY),319        })320    franchises.sort(key=lambda f: (-f["active_listings"], -f["brokers"]))321322    platforms = []323    for sid, inv in by_source.items():324        s = reg_by_id.get(sid, {})325        if sid in PLATFORM_IDS or s.get("type") in PLATFORM_TYPES:326            platforms.append({327                "id": sid, "name": s.get("name") or sid,328                "kind": s.get("type") or "petites annonces",329                "url": s.get("url") or None,330                **inv.out(), "last_sync": last_sync.get(sid),331            })332    platforms.sort(key=lambda p: -p["active_listings"])333334    regions: dict[str, dict] = {}335    for a in agencies:336        for rg in a["regions"]:337            e = regions.setdefault(rg, {"agencies": 0, "brokers": 0})338            e["agencies"] += 1339            e["brokers"] += a["brokers"]340    return {341        "generated": doc.get("generated"),342        "registry": doc.get("source"),343        # mêmes nombres que /api/bannieres : agences (hors l'entrée « courtiers344        # à leur compte »), courtiers en agence, courtiers à leur compte, total345        "total": len(agencies),346        "agencies_total": len(agencies),347        "with_listings": sum(1 for a in agencies if a["active_listings"]),348        "agency_brokers_total": sum(a["brokers"] for a in agencies),349        "independent_brokers": independents,350        "brokers_total": sum(a["brokers"] for a in agencies) + independents,351        "listings_total": total,352        "regions": [{"region": k, **v} for k, v in353                    sorted(regions.items(), key=lambda kv: -kv[1]["agencies"])],354        "franchises": franchises,355        "platforms": platforms,356        "agencies": agencies,357        "computed_at": time.time(),358    }359360361def compute() -> dict:362    """Annuaire en cache (10 min), recalcul à un seul fil."""363    cached = _CACHE["data"]364    if cached is not None and time.time() - _CACHE["ts"] < _TTL:365        return cached366    if not _LOCK.acquire(blocking=cached is None):367        return cached368    try:369        cached = _CACHE["data"]370        if cached is not None and time.time() - _CACHE["ts"] < _TTL:371            return cached372        data = _build()373        _CACHE.update(ts=time.time(), data=data)374        return data375    finally:376        _LOCK.release()377378379def agency(agency_id: str) -> dict | None:380    """Une agence de l'annuaire + la liste de ses courtiers (registre OACIQ)."""381    for a in compute()["agencies"]:382        if a["id"] == agency_id:383            from . import bannieres384            bannieres.load()385            full = (bannieres._cache["index"] or {}).get(agency_id) or {}386            return {**a, "brokers_list": full.get("brokers") or []}387    return None388
Files main
Menu

Theme