SPB Git

Repository Public

fb_marketplace.py 23.9 KB 526 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/fb_marketplace.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1713# Last Modified    : 2026-11-1214#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/fb_marketplace.py : Facebook Marketplace — catégorie location91#   (propertyrentals), TOUTE la province. Annonces de particuliers, fort92#   complément aux gestionnaires. Depuis 2026-08-22 le scraping est délégué à93#   l'ACTEUR APIFY MAISON gorgeous_thistle/ka-fb-marketplace (source :94#   actors/ka-fb-marketplace de ce repo) : HTML public déconnecté SANS rendu95#   JS (les JSON de recherche, la fiche PDP et la galerie MediaViewer96#   préchargée vivent dans le HTML brut) via proxy résidentiel CA — ~100×97#   moins cher que l'ancienne chaîne Scrapfly ASP+render_js, et couverture98#   élargie de 10 à 33 villes (IDs Marketplace des villes régionales validés ;99#   les slugs inventés retombent sur des villes aléatoires, ne pas en ajouter100#   sans les valider).101#   Le scroll infini reste bloqué hors connexion (~25 annonces/URL) : on102#   pagine par TRANCHES DE PRIX et on accumule sur plusieurs synchronisations.103#   Le flux public TOURNE : une phase de RATTRAPAGE (extraDetailIds) visite104#   les fiches actives jamais enrichies (budget LOUKA_FBMP_BACKFILL).105#   Le connecteur garde le cache détail BD (clé v2, payloads compatibles) et106#   passe à l'acteur la liste des fiches fraîches à NE PAS revisiter.107#   ⚠️ Données personnelles (Loi 25) : ne jamais republier nom/téléphone du108#   vendeur, garder le lien sortant.109#   2026-11-12 : le compte Apify gorgeous_thistle a disparu (token 401110#   « user-or-token-not-found », profil 404 par username ET par id) — l'acteur111#   est désormais exécuté LOCALEMENT (_fbmp_local.py : même code actors/,112#   curl_cffi + proxy résidentiel Oxylabs, Apify ne fournissait que le113#   compute). Repasser par Apify : LOUKA_FBMP_BACKEND=apify + APIFY_TOKEN.114# -----------------------------------------------------------------------------115from __future__ import annotations116117import json118import os119import re120import time121122import requests as _requests123124from ..schema import Listing, normalize_unit_type125from .base import BaseConnector126from . import _detailutil as du127from ._fbmp_local import run_actor_local128129BASE = "https://www.facebook.com/marketplace"130APIFY_API = "https://api.apify.com/v2"131ACTOR = os.environ.get("LOUKA_FBMP_ACTOR", "gorgeous_thistle~ka-fb-marketplace")132133# villes québécoises — gros parcs : slug vanity Marketplace -> nom d'affichage134CITIES = {135    "montreal": "Montréal", "laval": "Laval", "longueuil": "Longueuil",136    "quebec": "Québec", "gatineau": "Gatineau", "sherbrooke": "Sherbrooke",137    "trois-rivieres": "Trois-Rivières", "levis": "Lévis",138    "saguenay": "Saguenay", "drummondville": "Drummondville",139}140# villes régionales : ID numérique Marketplace -> nom (découverts via Serper,141# lat/lng validés live 2026-08-22 — rayon ~65 km chacun)142REGIONS = {143    "105790762794728": "Rimouski", "110925022261358": "Rivière-du-Loup",144    "106528256049537": "Matane", "109502305742889": "Gaspé",145    "100246746683723": "Sept-Îles", "105615529471535": "Baie-Comeau",146    "106016152771864": "Rouyn-Noranda", "110594102301488": "Val-d'Or",147    "105598479473872": "Amos", "109699385723610": "Saint-Georges",148    "110304502331480": "Thetford Mines", "111938355489908": "Granby",149    "108126699220609": "Victoriaville", "109753249050671": "Joliette",150    "109429165750459": "Saint-Hyacinthe",151    "108645709159963": "Saint-Jean-sur-Richelieu",152    "112946182053396": "Saint-Jérôme",153    "113011352052118": "Salaberry-de-Valleyfield",154    "107992819229760": "Magog", "109514615734434": "Alma",155    "109664672393669": "Mont-Laurier", "108557812502323": "La Tuque",156    "108296932538245": "Dolbeau-Mistassini",157}158# tranches de prix (bornes en $) : le flux déconnecté sert un sous-ensemble159# tournant, chaque tranche renvoie un lot quasi disjoint160PRICE_BANDS = [(0, 800), (800, 1100), (1100, 1400), (1400, 1700),161               (1700, 2100), (2100, 2800), (2800, 6000)]162REGIONAL_BANDS = [(0, 1200), (1200, 6000)]   # parcs plus petits : 2 tranches163164# garde-fous de prix mensuel (rejette « $90 » = /nuit, et les valeurs à vendre)165PRICE_MIN, PRICE_MAX = 300, 12000166167DETAIL_LIMIT = int(os.environ.get("LOUKA_FBMP_DETAIL_LIMIT", "120"))168# rattrapage : fiches ACTIVES en BD encore pauvres (sans description, sans169# GPS ou avec ≤ 1 image) qui ne repassent plus dans la recherche publique170BACKFILL_LIMIT = int(os.environ.get("LOUKA_FBMP_BACKFILL", "80"))171# les annonces FB changent peu après publication : TTL long = le budget détail172# sert surtout aux NOUVELLES annonces plutôt qu'à re-visiter les connues173TTL_DAYS = float(os.environ.get("LOUKA_FBMP_TTL_DAYS", "30"))174CITY_LIMIT = os.environ.get("LOUKA_FBMP_CITIES", "")   # ex. "montreal,laval"175CONCURRENCY = int(os.environ.get("LOUKA_FBMP_CONCURRENCY", "8"))176RUN_TIMEOUT = int(os.environ.get("LOUKA_FBMP_RUN_TIMEOUT", "2400"))  # s177# "local" (défaut depuis 2026-11-12, compte Apify disparu) ou "apify"178BACKEND = os.environ.get("LOUKA_FBMP_BACKEND", "local")179180# clé du cache détail — v2 : payloads identiques à l'ère Scrapfly (galerie,181# ville/province, statut) ; l'acteur produit la même forme, cache réutilisé182DETAIL_KEY = "v2"183184# provinces acceptées : le flux public glisse parfois des annonces hors Québec185# (ex. « Norfolk, ON ») dans les résultats d'une ville québécoise186_QC_STATES = {"qc", "quebec", "québec"}187188189def _unit_type(title: str, desc: str = "") -> str:190    blob = f"{title} {desc}"191    ut = normalize_unit_type(title)192    if re.match(r"^\d½$|^6½\+$|^Studio$|^Loft$", ut or ""):193        return ut194    m = re.search(r"(\d+)\s*(?:bed|bedroom|chambre|cc|br)\b", blob, re.I)195    if m:196        n = int(m.group(1)) + 2197        return "6½+" if n >= 6 else f"{n}½"198    if re.search(r"\bstudio|bachelor\b", blob, re.I):199        return "Studio"200    if re.search(r"\b(?:private\s+)?room\b|chambre", blob, re.I):201        return "Chambre"202    return ""203204205def _usable(payload: dict | None) -> bool:206    """Payload détail exploitable (ni vide, ni marqueur « fiche sans objet »)."""207    return bool(payload) and not payload.get("nopdp")208209210def _non_qc(payload: dict) -> bool:211    state = (payload.get("state") or "").strip().lower()212    if state:213        return state not in _QC_STATES214    # sans état : filet géographique — certains PDP ne livrent que le GPS215    lat, lng = payload.get("lat"), payload.get("lng")216    if lat is not None and lng is not None:217        return not (44.9 <= lat <= 62.8 and -79.6 <= lng <= -56.9)218    return False219220221# version des payloads détail : bump quand parse_detail (acteur) apprend de222# nouveaux champs, pour re-visiter progressivement les fiches déjà en cache223PAYLOAD_VERSION = 3224225_TYPE_LABELS = {"apartment", "house", "townhouse", "condo", "room", "flat",226                "appartement", "maison", "maison de ville", "chambre", "loft"}227_BEDS_RX = re.compile(r"(\d+(?:[.,]\d+)?)\s*(?:beds?\b|chambres?\b|lits?\b)",228                      re.I)229_BATHS_RX = re.compile(r"(\d+(?:[.,]\d+)?)\s*(?:baths?\b|salles?\b)", re.I)230231232def _std_detail(d: dict) -> dict:233    """Payload acteur -> dict pour du.apply_detail (labels PDP en/fr)."""234    std = {k: d[k] for k in ("description", "images", "lat", "lng",235                             "city", "address") if d.get(k)}236    amen: list[str] = []237    for lbl in d.get("unit_fields") or []:238        mb = _BEDS_RX.search(lbl)239        if mb:                          # « 2 beds · 1 bath »240            std["bedrooms"] = float(mb.group(1).replace(",", "."))241            ms = _BATHS_RX.search(lbl)242            if ms:243                std["bathrooms"] = float(ms.group(1).replace(",", "."))244            continue245        low = lbl.casefold()246        if low in _TYPE_LABELS:247            continue        # type générique : _unit_type (titre/desc) fait mieux248        if "furnish" in low or "meublé" in low:249            std["furnished"] = not ("unfurnish" in low or "non meublé" in low)250        if "pet" in low or "animaux" in low:251            std["pets"] = ("non" if "no pet" in low or "pas d" in low252                           else "oui")253        amen.append(lbl)254    if amen:255        std["amenities"] = amen256    for part in (d.get("listed_text") or "").split("·"):257        p = part.strip()258        if p.casefold().startswith(("available", "disponible")):259            std["availability"] = p260    extras = {k: d[k] for k in ("walk_score", "transit_score", "bike_score")261              if d.get(k) is not None}262    if d.get("virtual_tour_url"):263        extras["virtual_tour"] = d["virtual_tour_url"]264    if extras:265        std["details"] = extras266    return std267268269class FacebookMarketplaceConnector(BaseConnector):270    source_id = "fb_marketplace"271    request_delay = 1.0272273    # -- orchestration de l'acteur Apify --------------------------------------274    def _search_urls(self) -> tuple[list[str], dict[str, str]]:275        """URLs de recherche (ville × tranche) + mapping URL -> nom de ville."""276        cities, regions = dict(CITIES), dict(REGIONS)277        if CITY_LIMIT:278            wanted = {c.strip().casefold() for c in CITY_LIMIT.split(",")}279            cities = {k: v for k, v in cities.items()280                      if k in wanted or v.casefold() in wanted}281            regions = {k: v for k, v in regions.items()282                       if v.casefold() in wanted}283        urls: list[str] = []284        by_url: dict[str, str] = {}285        for slug, city in cities.items():286            for lo, hi in PRICE_BANDS:287                u = (f"{BASE}/{slug}/propertyrentals"288                     f"?minPrice={lo}&maxPrice={hi}&sortBy=creation_time_descend")289                urls.append(u)290                by_url[u] = city291        for cid, city in regions.items():292            for lo, hi in REGIONAL_BANDS:293                u = (f"{BASE}/{cid}/propertyrentals"294                     f"?minPrice={lo}&maxPrice={hi}&sortBy=creation_time_descend")295                urls.append(u)296                by_url[u] = city297        return urls, by_url298299    def _run_actor(self, payload: dict, token: str) -> list[dict]:300        """Lance l'acteur, attend la fin, retourne les items du dataset."""301        r = _requests.post(302            f"{APIFY_API}/acts/{ACTOR}/runs?waitForFinish=120",303            json=payload, timeout=180,304            headers={"Authorization": f"Bearer {token}"})305        r.raise_for_status()306        run = r.json()["data"]307        deadline = time.time() + RUN_TIMEOUT308        while run["status"] in ("READY", "RUNNING") and time.time() < deadline:309            time.sleep(10)310            run = _requests.get(311                f"{APIFY_API}/actor-runs/{run['id']}", timeout=60,312                headers={"Authorization": f"Bearer {token}"}).json()["data"]313        if run["status"] != "SUCCEEDED":314            raise RuntimeError(f"acteur {ACTOR} : run {run['id']} "315                               f"terminé en {run['status']}")316        items: list[dict] = []317        offset = 0318        while True:319            batch = _requests.get(320                f"{APIFY_API}/datasets/{run['defaultDatasetId']}/items"321                f"?limit=1000&offset={offset}", timeout=120,322                headers={"Authorization": f"Bearer {token}"}).json()323            items.extend(batch)324            if len(batch) < 1000:325                return items326            offset += 1000327328    # -- caches / BD -----------------------------------------------------------329    def _fresh_ids(self, cache: du.TtlDetailCache) -> list[str]:330        """IDs dont le payload détail en cache est encore frais (clé + TTL) :331        l'acteur ne les revisitera pas."""332        rows = cache.con.execute(333            "SELECT external_id FROM detail_cache"334            " WHERE source=? AND key=? AND fetched_at > ?"335            " AND (json_extract(payload,'$.pv') >= ?"336            "      OR json_extract(payload,'$.nopdp') IS NOT NULL"337            "      OR json_extract(payload,'$.gone') IS NOT NULL)",338            (self.source_id, DETAIL_KEY,339             time.time() - TTL_DAYS * 86400, PAYLOAD_VERSION)).fetchall()340        return [r["external_id"] for r in rows]341342    def _poor_active_rows(self, cache: du.TtlDetailCache) -> list:343        """Fiches ACTIVES en BD encore pauvres (candidates au rattrapage)."""344        rows = cache.con.execute(345            "SELECT external_id, url, title, address, sector, city, unit_type,"346            " bedrooms, bathrooms, price, price_label, availability,"347            " availability_date, area_sqft, pets, furnished, description,"348            " amenities, details, images, lat, lng"349            " FROM listings WHERE source=? AND active=1"350            " ORDER BY last_seen DESC", (self.source_id,)).fetchall()351352        def poor(r) -> bool:353            try:354                n_img = len(json.loads(r["images"] or "[]"))355            except ValueError:356                n_img = 0357            return (not (r["description"] or "").strip()358                    or r["lat"] is None or n_img <= 1359                    or not (r["address"] or "").strip()360                    or r["bedrooms"] is None)361        return [r for r in rows if poor(r)]362363    def _listing_from_row(self, r) -> Listing:364        """Reconstruit le Listing depuis sa ligne BD (phase de rattrapage)."""365        def js(s, default):366            try:367                return json.loads(s) if s else default368            except ValueError:369                return default370        return Listing(371            source=self.source_id, external_id=r["external_id"],372            url=r["url"], title=r["title"] or "", address=r["address"] or "",373            sector=r["sector"] or "", city=r["city"] or "",374            unit_type=r["unit_type"] or "", bedrooms=r["bedrooms"],375            bathrooms=r["bathrooms"], price=r["price"],376            price_label=r["price_label"] or "",377            availability=r["availability"] or "",378            availability_date=r["availability_date"],379            area_sqft=r["area_sqft"], pets=r["pets"],380            furnished=(None if r["furnished"] is None else bool(r["furnished"])),381            description=r["description"] or "",382            amenities=js(r["amenities"], []), details=js(r["details"], {}),383            images=js(r["images"], []), lat=r["lat"], lng=r["lng"],384        )385386    def _backfill(self, cache: du.TtlDetailCache, poor_rows: list,387                  done: set[str]) -> list[Listing]:388        """Rattrapage : ré-émet les fiches actives pauvres dont le cache389        (rempli par l'acteur via extraDetailIds) apporte du neuf. Les390        annonces mortes suivent le cycle normal miss_count → retrait."""391        def adds(r, s: dict) -> bool:392            if s.get("description") and len(s["description"]) > \393                    len(r["description"] or ""):394                return True395            if s.get("lat") is not None and r["lat"] is None:396                return True397            try:398                n_img = len(json.loads(r["images"] or "[]"))399            except ValueError:400                n_img = 0401            if len(s.get("images") or []) > n_img:402                return True403            if s.get("address") and not (r["address"] or "").strip():404                return True405            if s.get("bedrooms") is not None and r["bedrooms"] is None:406                return True407            return bool(s.get("city")) and not (r["city"] or "")408409        out: list[Listing] = []410        for r in poor_rows:411            if r["external_id"] in done:412                continue413            d, _fresh = cache.peek(r["external_id"])414            if not _usable(d) or d.get("gone") or _non_qc(d):415                continue                       # morte / hors QC / rien de neuf416            std = _std_detail(d)417            if not adds(r, std):418                continue           # rien à apporter : laisser vivre son cycle419            lst = self._listing_from_row(r)420            du.apply_detail(lst, std)421            if d.get("city"):                  # reverse geocode FB : autoritaire422                lst.city = d["city"]423            if not lst.unit_type:424                lst.unit_type = _unit_type(lst.title, lst.description)425            out.append(lst)426        return out427428    # -- pipeline principal ----------------------------------------------------429    def fetch(self) -> list[Listing]:430        token = os.environ.get("APIFY_TOKEN")431        if BACKEND == "apify" and not token:432            raise RuntimeError("APIFY_TOKEN manquant (voir .env)")433        urls, city_by_url = self._search_urls()434435        cache = du.TtlDetailCache(self, budget=0, ttl_days=TTL_DAYS,436                                  key=DETAIL_KEY, fetch_html=lambda _u: "")437        try:438            fresh = set(self._fresh_ids(cache))439            poor_rows = self._poor_active_rows(cache)440            extra = [r["external_id"] for r in poor_rows441                     if r["external_id"] not in fresh][:BACKFILL_LIMIT]442443            actor_input: dict = {444                "searchUrls": urls,445                "getDetails": True,446                "maxDetails": DETAIL_LIMIT + BACKFILL_LIMIT,447                "skipDetailIds": sorted(fresh),448                "extraDetailIds": extra,449                "concurrency": CONCURRENCY,450                "requestDelay": 1,451            }452            # abonnement résidentiel Oxylabs (déjà payé) plutôt que le proxy453            # Apify facturé au Go ; l'acteur retombe sur Apify RESIDENTIAL454            # si le gabarit est absent455            ox_u = os.environ.get("OXYLABS_PROXY_USER")456            ox_p = os.environ.get("OXYLABS_PROXY_PASS")457            if ox_u and ox_p:458                actor_input["proxyUrlTemplate"] = (459                    f"http://{ox_u}-cc-CA-sessid-{{session}}:{ox_p}"460                    f"@pr.oxylabs.io:7777")461462            items = (self._run_actor(actor_input, token)463                     if BACKEND == "apify" else run_actor_local(actor_input))464465            # payloads détail -> cache BD (mêmes formes/clés que l'ère Scrapfly)466            for it in items:467                if it.get("kind") != "detail":468                    continue469                if not it.get("ok"):470                    continue               # échec réseau acteur : pas de cache471                payload = {k: v for k, v in it.items()472                           if k not in ("kind", "id", "ok") and v is not None}473                if payload and not payload.get("nopdp"):474                    payload["pv"] = PAYLOAD_VERSION475                cache.put(str(it["id"]), payload or {"nopdp": True})476477            out: dict[str, Listing] = {}478            for it in items:479                if it.get("kind") != "listing":480                    continue481                lid = str(it["id"])482                price = it.get("price")483                if price is None or not (PRICE_MIN <= price <= PRICE_MAX):484                    continue           # sans prix mensuel valable : ignorer485                if it.get("is_sold") or it.get("is_pending"):486                    continue           # déjà loué / en attente487                if _non_qc(it):488                    continue           # suggestion FB hors Québec dès la recherche489                detail, _f = cache.peek(lid)490                detail = detail if _usable(detail) else {}491                if detail.get("gone"):492                    continue           # la fiche dit : loué / retiré493                if detail and _non_qc(detail):494                    continue           # annonce hors Québec glissée dans le flux495                title = it.get("title") or ""496                desc = detail.get("description") or ""497                photo = it.get("primary_photo") or ""498                images = detail.get("images") or ([photo] if photo else [])499                city = (detail.get("city") or it.get("city")500                        or city_by_url.get(it.get("source_url") or "", ""))501                lst = Listing(502                    source=self.source_id,503                    external_id=lid,504                    url=f"{BASE}/item/{lid}/",505                    title=title[:200],506                    city=city,507                    unit_type=_unit_type(title, desc),508                    price=float(price),509                    price_label=f"{price:,.0f} $/mois".replace(",", " "),510                    description=desc,511                    images=images,512                    lat=detail.get("lat"),513                    lng=detail.get("lng"),514                )515                # champs structurés du PDP : adresse, chambres/sdb, commodités,516                # disponibilité, scores de marche/transport517                du.apply_detail(lst, _std_detail(detail))518                out[lid] = lst519520            listings = list(out.values())521            # rattrapage des fiches actives pauvres sorties de la recherche522            listings.extend(self._backfill(cache, poor_rows, set(out)))523        finally:524            cache.close()525        return listings526
Files main
Menu

Theme