SPB Git

Repository Public

main.py 17.6 KB 439 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : actors/ka-fb-marketplace/src/main.py10# Module           : actors11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2213# Last Modified    : 2026-08-2214#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# Author: Simon-Pierre Boucher <contact@spboucher.ai>89# File:   src/main.py (ka-fb-marketplace)90# Desc:   Facebook Marketplace — logements à louer (propertyrentals), Québec.91#         Scraping public DÉCONNECTÉ, AUCUN rendu JS : les données vivent dans92#         les <script type="application/json"> du HTML brut.93#         - Recherche : objets marketplace_listing_title (~25/URL, on multiplie94#           les URLs ville × tranche de prix pour élargir).95#         - Fiche /marketplace/item/<id> : le target GraphQL préchargé96#           (marketplace_product_details_page) expose GPS, ville97#           (reverse_geocode_detailed), description, statut is_live/is_sold ;98#           la GALERIE complète vient du target MediaViewer préchargé99#           (listing_photos du même id) — validé live, aucun rendu requis.100#         Sortie dataset : {kind:"listing"} (recherche) et {kind:"detail"}.101#         ⚠️ Données personnelles (Loi 25) : ne jamais republier nom/téléphone102#         du vendeur ; le champ seller n'est PAS extrait.103# ==============================================================================104from __future__ import annotations105106import asyncio107import html as _html108import json109import re110111from apify import Actor112113from .net import Fetcher114115BASE = "https://www.facebook.com/marketplace"116117# Couverture Québec par défaut (mode autonome, sans searchUrls) :118# slug vanity OU id numérique Marketplace (validés live 2026-08-22 — les slugs119# inventés retombent sur des villes aléatoires, seuls ceux-ci sont sûrs).120# Chaque recherche couvre un rayon d'environ 65 km.121BIG_CITIES = {  # gros parcs : tranches de prix fines (flux ~25 annonces/URL)122    "montreal": "Montréal", "laval": "Laval", "longueuil": "Longueuil",123    "quebec": "Québec", "gatineau": "Gatineau", "sherbrooke": "Sherbrooke",124    "trois-rivieres": "Trois-Rivières", "levis": "Lévis",125    "saguenay": "Saguenay", "drummondville": "Drummondville",126}127REGIONAL_CITIES = {  # couverture régions : ids numériques (Serper + validation)128    "105790762794728": "Rimouski", "110925022261358": "Rivière-du-Loup",129    "106528256049537": "Matane", "109502305742889": "Gaspé",130    "100246746683723": "Sept-Îles", "105615529471535": "Baie-Comeau",131    "106016152771864": "Rouyn-Noranda", "110594102301488": "Val-d'Or",132    "105598479473872": "Amos", "109699385723610": "Saint-Georges",133    "110304502331480": "Thetford Mines", "111938355489908": "Granby",134    "108126699220609": "Victoriaville", "109753249050671": "Joliette",135    "109429165750459": "Saint-Hyacinthe",136    "108645709159963": "Saint-Jean-sur-Richelieu",137    "112946182053396": "Saint-Jérôme", "113011352052118": "Salaberry-de-Valleyfield",138    "107992819229760": "Magog", "109514615734434": "Alma",139    "109664672393669": "Mont-Laurier", "108557812502323": "La Tuque",140    "108296932538245": "Dolbeau-Mistassini",141}142PRICE_BANDS = [(0, 800), (800, 1100), (1100, 1400), (1400, 1700),143               (1700, 2100), (2100, 2800), (2800, 6000)]144REGIONAL_BANDS = [(0, 1200), (1200, 6000)]   # parcs plus petits : 2 tranches145146_SCRIPT_RE = re.compile(147    r'<script type="application/json"[^>]*>(.*?)</script>', re.S)148149150def default_search_urls() -> list[str]:151    urls = []152    for slug in BIG_CITIES:153        for lo, hi in PRICE_BANDS:154            urls.append(f"{BASE}/{slug}/propertyrentals"155                        f"?minPrice={lo}&maxPrice={hi}"156                        f"&sortBy=creation_time_descend")157    for cid in REGIONAL_CITIES:158        for lo, hi in REGIONAL_BANDS:159            urls.append(f"{BASE}/{cid}/propertyrentals"160                        f"?minPrice={lo}&maxPrice={hi}"161                        f"&sortBy=creation_time_descend")162    return urls163164165def _iter_json_scripts(html: str):166    for m in _SCRIPT_RE.finditer(html):167        try:168            yield json.loads(m.group(1))169        except ValueError:170            continue171172173def walk_listings(html: str) -> dict:174    """Objets d'annonce (marketplace_listing_title) des <script> JSON."""175    out: dict = {}176177    def walk(o):178        if isinstance(o, dict):179            if "marketplace_listing_title" in o and o.get("id"):180                out.setdefault(str(o["id"]), o)181            for v in o.values():182                walk(v)183        elif isinstance(o, list):184            for v in o:185                walk(v)186187    for data in _iter_json_scripts(html):188        walk(data)189    return out190191192def price_of(obj: dict) -> float | None:193    """Montant du loyer depuis listing_price (offset en cents géré)."""194    pr = obj.get("listing_price") or {}195    for k in ("amount", "amount_with_offset_in_currency"):196        v = pr.get(k)197        if v is None:198            continue199        try:200            val = float(v)201        except (TypeError, ValueError):202            continue203        if k == "amount_with_offset_in_currency" and val > 100000:204            val /= 100.0205        if val > 0:206            return round(val, 0)207    return None208209210def _pdp_target(html: str) -> dict | None:211    """Nœud cible le plus RICHE (description/GPS/statut) parmi les targets212    marketplace_product_details_page préchargés (stubs inclus)."""213    found: list[dict] = []214215    def walk(o):216        if isinstance(o, dict):217            pdp = o.get("marketplace_product_details_page")218            if isinstance(pdp, dict) and isinstance(pdp.get("target"), dict):219                found.append(pdp["target"])220            for v in o.values():221                walk(v)222        elif isinstance(o, list):223            for v in o:224                walk(v)225226    for data in _iter_json_scripts(html):227        walk(data)228229    def score(t: dict) -> tuple:230        desc = (t.get("redacted_description") or {}).get("text") or ""231        loc = t.get("location") or {}232        return (1 if desc else 0) + (1 if loc.get("latitude") else 0), len(t)233    return max(found, key=score) if found else None234235236def _gallery(html: str, lid: str) -> list[str]:237    """Galerie complète : plus grand tableau listing_photos porté par un objet238    du MÊME id (le target MediaViewer préchargé la contient hors connexion)."""239    best: list[str] = []240241    def walk(o):242        nonlocal best243        if isinstance(o, dict):244            lp = o.get("listing_photos")245            if (isinstance(lp, list) and lp246                    and str(o.get("id") or "") == lid):247                uris = []248                for p in lp:249                    uri = ((p.get("image") or {}).get("uri")250                           if isinstance(p, dict) else "") or ""251                    if uri and uri not in uris:252                        uris.append(uri)253                if len(uris) > len(best):254                    best = uris255            for v in o.values():256                walk(v)257        elif isinstance(o, list):258            for v in o:259                walk(v)260261    for data in _iter_json_scripts(html):262        walk(data)263    return best264265266def _clean_desc(text: str) -> str:267    t = text.replace("\r", "\n")268    t = re.sub(r"[ \t ]+", " ", t)269    t = re.sub(r" ?\n ?", "\n", t)270    t = re.sub(r"\n{3,}", "\n\n", t)271    return t.strip()272273274def parse_detail(html: str, lid: str) -> dict:275    """Champs riches d'une fiche /marketplace/item/<id> hors connexion.276277    {} si la page n'a pas pu être rendue (échec réseau : l'appelant ne doit278    PAS mettre en cache), {"nopdp": True} si rendue mais sans objet cible279    (fiche supprimée / mur de login : cacher pour ne pas boucler)."""280    if not html:281        return {}282    o = _pdp_target(html)283    if not o:284        return {"nopdp": True}285    out: dict = {}286    if o.get("is_sold") or o.get("is_pending") or o.get("is_live") is False:287        out["gone"] = True              # loué / en attente / retiré288    loc = o.get("location") or {}289    if loc.get("latitude") and loc.get("longitude"):290        out["lat"] = loc["latitude"]291        out["lng"] = loc["longitude"]292    geo = loc.get("reverse_geocode_detailed") or {}293    if geo.get("city"):294        out["city"] = geo["city"]295    if geo.get("state"):296        out["state"] = geo["state"]297    lt = (o.get("location_text") or {}).get("text") or ""298    if lt:                              # ex. « Québec, QC » / « Norfolk, ON »299        out["location_text"] = lt300        parts = [p.strip() for p in lt.split(",") if p.strip()]301        if parts and not out.get("city"):302            out["city"] = parts[0]303        if len(parts) > 1 and not out.get("state"):304            out["state"] = parts[1]305    desc = (o.get("redacted_description") or {}).get("text") or ""306    if desc:307        out["description"] = _clean_desc(desc)[:6000]308    addr = ((o.get("home_address") or {}).get("street") or "").strip()309    unit_fields: list[str] = []310    for sec in (o.get("pdp_display_sections") or []):311        stype = sec.get("section_type") or ""312        for f in (sec.get("pdp_fields") or []):313            lbl = (f.get("display_label") or "").strip()314            if not lbl:315                continue316            if stype == "UNIT_INCLUDES":317                unit_fields.append(lbl)318            elif stype == "UNIT_SUBTITLE":319                if (f.get("icon_name") or "") == "pin" and not addr:320                    addr = lbl.split(",")[0].strip()321                elif (f.get("icon_name") or "") == "clock":322                    out["listed_text"] = lbl323    if addr:324        out["address"] = addr325    if unit_fields:326        out["unit_fields"] = unit_fields327    for src_k, dst_k in (("walk_score_info", "walk_score"),328                         ("transit_score_info", "transit_score"),329                         ("bike_score_info", "bike_score")):330        sc = (o.get(src_k) or {}).get("score")331        if sc is not None:332            out[dst_k] = sc333    if o.get("virtual_tour_url"):334        out["virtual_tour_url"] = o["virtual_tour_url"]335    photos = _gallery(html, lid)336    if photos:337        out["images"] = photos338    return out339340341async def main() -> None:342    async with Actor:343        inp = await Actor.get_input() or {}344        search_urls = [u for u in (inp.get("searchUrls") or []) if u]345        if not search_urls:346            search_urls = default_search_urls()347        get_details = inp.get("getDetails", True)348        max_details = int(inp.get("maxDetails") or 200)349        skip_ids = {str(i) for i in (inp.get("skipDetailIds") or [])}350        extra_ids = [str(i) for i in (inp.get("extraDetailIds") or [])]351        template = (inp.get("proxyUrlTemplate") or "").strip() or None352        proxy = None353        if not template:354            proxy = await Actor.create_proxy_configuration(355                actor_proxy_input=inp.get("proxyConfiguration"))356        fetcher = Fetcher(proxy, delay=float(inp.get("requestDelay") or 1),357                          proxy_template=template)358        sem = asyncio.Semaphore(int(inp.get("concurrency") or 8))359360        # -- phase recherche ---------------------------------------------------361        found: dict[str, tuple[dict, str]] = {}   # id -> (objet, source_url)362        fails = 0363364        async def search(url: str) -> None:365            nonlocal fails366            async with sem:367                try:368                    resp = await fetcher.get(url, session_id=f"q{hash(url)}")369                except Exception as exc:370                    fails += 1371                    Actor.log.warning(f"recherche KO {url} : {exc}")372                    return373                if resp.status_code != 200:374                    fails += 1375                    return376                for lid, obj in walk_listings(resp.text).items():377                    found.setdefault(lid, (obj, url))378379        await asyncio.gather(*[search(u) for u in search_urls])380        Actor.log.info(f"recherche : {len(found)} annonces uniques "381                       f"({len(search_urls)} URLs, {fails} échecs)")382383        for lid, (obj, src) in found.items():384            photo = ((obj.get("primary_listing_photo") or {})385                     .get("image") or {}).get("uri") or ""386            loc = obj.get("location") or {}387            geo = loc.get("reverse_geocode") or {}388            await Actor.push_data({389                "kind": "listing",390                "id": lid,391                "title": (obj.get("marketplace_listing_title") or "")[:300],392                "price": price_of(obj),393                "city": (geo.get("city")394                         or (geo.get("city_page") or {}).get("display_name")395                         or ""),396                "state": geo.get("state") or "",397                "primary_photo": photo,398                "is_sold": bool(obj.get("is_sold")),399                "is_pending": bool(obj.get("is_pending")),400                "source_url": src,401                "url": f"{BASE}/item/{lid}/",402            })403404        # -- phase détail ------------------------------------------------------405        if not get_details or max_details <= 0:406            return407        todo: list[str] = []408        for lid, (obj, _src) in found.items():409            if lid in skip_ids or obj.get("is_sold") or obj.get("is_pending"):410                continue411            if price_of(obj) is None:412                continue               # sans prix : jamais publiable, épargner413            # le flux public glisse des annonces d'autres provinces (suggestions)414            geo = (obj.get("location") or {}).get("reverse_geocode") or {}415            st = (geo.get("state") or "").strip().lower()416            if st and st not in ("qc", "quebec", "québec"):417                continue418            todo.append(lid)419        for lid in extra_ids:          # rattrapage : après les nouveautés420            if lid not in todo and lid not in skip_ids:421                todo.append(lid)422        todo = todo[:max_details]423424        async def detail(lid: str) -> None:425            async with sem:426                try:427                    resp = await fetcher.get(f"{BASE}/item/{lid}/",428                                             session_id=f"d{lid}")429                    payload = parse_detail(430                        resp.text if resp.status_code == 200 else "", lid)431                except Exception as exc:432                    Actor.log.warning(f"détail KO {lid} : {exc}")433                    payload = {}434                await Actor.push_data({"kind": "detail", "id": lid,435                                       "ok": bool(payload), **payload})436437        await asyncio.gather(*[detail(lid) for lid in todo])438        Actor.log.info(f"détail : {len(todo)} fiches visitées")439
Files main
Menu

Theme