Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/_fbmp_local.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-11-1213# 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/_fbmp_local.py : exécution LOCALE de l'acteur Apify maison91# ka-fb-marketplace (source : actors/ka-fb-marketplace de ce repo).92# Depuis 2026-11-12 le compte Apify gorgeous_thistle ne répond plus93# (token 401 « user-or-token-not-found », profil 404 par username ET par id) :94# Apify ne fournissait que le compute — le réseau passait déjà par le proxy95# résidentiel Oxylabs via proxyUrlTemplate — donc on exécute le MÊME code96# d'acteur dans le process de sync, avec curl_cffi (empreinte TLS Chrome).97# Le code de l'acteur reste la source de vérité : on le charge depuis98# actors/ka-fb-marketplace/src (shim `apify` minimal pour Actor.log) et on99# rejoue les deux phases de son main() (recherche puis détail) en collectant100# les items dans une liste au lieu du dataset Apify — mêmes formes101# {kind:"listing"} / {kind:"detail"}, le connecteur ne voit pas la différence.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import asyncio106import importlib.util107import logging108import sys109import types110from pathlib import Path111112log = logging.getLogger("louka.fb_marketplace.actor")113114_SRC = (Path(__file__).resolve().parents[2]115 / "actors" / "ka-fb-marketplace" / "src")116_PKG = "ka_fbmp_actor"117_mods: dict[str, types.ModuleType] = {}118119120def _load_actor() -> dict[str, types.ModuleType]:121 """Charge net.py + main.py de l'acteur (une seule fois par process)."""122 if _mods:123 return _mods124 try: # le SDK Apify n'est pas dans le venv :125 import apify # noqa: F401 — shim minimal (Actor.log)126 except ImportError:127 shim = types.ModuleType("apify")128129 class _Actor:130 log = log131 shim.Actor = _Actor132 sys.modules["apify"] = shim133 pkg = types.ModuleType(_PKG)134 pkg.__path__ = [str(_SRC)] # paquet synthétique : `from .net import`135 sys.modules[_PKG] = pkg136 for name in ("net", "main"): # net d'abord (main l'importe)137 spec = importlib.util.spec_from_file_location(138 f"{_PKG}.{name}", _SRC / f"{name}.py")139 mod = importlib.util.module_from_spec(spec)140 sys.modules[f"{_PKG}.{name}"] = mod141 spec.loader.exec_module(mod)142 _mods[name] = mod143 return _mods144145146async def _amain(inp: dict) -> list[dict]:147 """Rejoue main() de l'acteur hors Apify ; retourne les items du dataset."""148 mods = _load_actor()149 net, m = mods["net"], mods["main"]150151 search_urls = [u for u in (inp.get("searchUrls") or []) if u]152 if not search_urls:153 search_urls = m.default_search_urls()154 get_details = inp.get("getDetails", True)155 max_details = int(inp.get("maxDetails") or 200)156 skip_ids = {str(i) for i in (inp.get("skipDetailIds") or [])}157 extra_ids = [str(i) for i in (inp.get("extraDetailIds") or [])]158 template = (inp.get("proxyUrlTemplate") or "").strip() or None159 if not template: # pas de proxy Apify en local : erreur160 raise RuntimeError( # franche plutôt que griller l'IP du nœud161 "fb_marketplace local : proxyUrlTemplate requis "162 "(OXYLABS_PROXY_USER/PASS manquants dans .env ?)")163 fetcher = net.Fetcher(None, delay=float(inp.get("requestDelay") or 1),164 proxy_template=template)165 sem = asyncio.Semaphore(int(inp.get("concurrency") or 8))166 items: list[dict] = []167168 # -- phase recherche (copie de main() : push_data -> items.append) --------169 found: dict[str, tuple[dict, str]] = {} # id -> (objet, source_url)170 fails = 0171172 async def search(url: str) -> None:173 nonlocal fails174 async with sem:175 try:176 resp = await fetcher.get(url, session_id=f"q{hash(url)}")177 except Exception as exc:178 fails += 1179 log.warning(f"recherche KO {url} : {exc}")180 return181 if resp.status_code != 200:182 fails += 1183 return184 for lid, obj in m.walk_listings(resp.text).items():185 found.setdefault(lid, (obj, url))186187 await asyncio.gather(*[search(u) for u in search_urls])188 log.info(f"recherche : {len(found)} annonces uniques "189 f"({len(search_urls)} URLs, {fails} échecs)")190 # zéro silencieux interdit : aucune annonce sur ~100 URLs de recherche =191 # proxy mort ou gabarit FB remanié, jamais un vrai zéro (médiane ~780)192 if not found:193 raise RuntimeError(194 f"fb_marketplace local : 0 annonce sur {len(search_urls)} URLs "195 f"de recherche ({fails} échecs réseau) — panne proxy ou gabarit")196197 for lid, (obj, src) in found.items():198 photo = ((obj.get("primary_listing_photo") or {})199 .get("image") or {}).get("uri") or ""200 loc = obj.get("location") or {}201 geo = loc.get("reverse_geocode") or {}202 items.append({203 "kind": "listing",204 "id": lid,205 "title": (obj.get("marketplace_listing_title") or "")[:300],206 "price": m.price_of(obj),207 "city": (geo.get("city")208 or (geo.get("city_page") or {}).get("display_name")209 or ""),210 "state": geo.get("state") or "",211 "primary_photo": photo,212 "is_sold": bool(obj.get("is_sold")),213 "is_pending": bool(obj.get("is_pending")),214 "source_url": src,215 "url": f"{m.BASE}/item/{lid}/",216 })217218 # -- phase détail (copie de main()) ---------------------------------------219 if not get_details or max_details <= 0:220 return items221 todo: list[str] = []222 for lid, (obj, _src) in found.items():223 if lid in skip_ids or obj.get("is_sold") or obj.get("is_pending"):224 continue225 if m.price_of(obj) is None:226 continue # sans prix : jamais publiable, épargner227 # le flux public glisse des annonces d'autres provinces (suggestions)228 geo = (obj.get("location") or {}).get("reverse_geocode") or {}229 st = (geo.get("state") or "").strip().lower()230 if st and st not in ("qc", "quebec", "québec"):231 continue232 todo.append(lid)233 for lid in extra_ids: # rattrapage : après les nouveautés234 if lid not in todo and lid not in skip_ids:235 todo.append(lid)236 todo = todo[:max_details]237238 async def detail(lid: str) -> None:239 async with sem:240 try:241 resp = await fetcher.get(f"{m.BASE}/item/{lid}/",242 session_id=f"d{lid}")243 payload = m.parse_detail(244 resp.text if resp.status_code == 200 else "", lid)245 except Exception as exc:246 log.warning(f"détail KO {lid} : {exc}")247 payload = {}248 items.append({"kind": "detail", "id": lid,249 "ok": bool(payload), **payload})250251 await asyncio.gather(*[detail(lid) for lid in todo])252 log.info(f"détail : {len(todo)} fiches visitées")253 return items254255256def run_actor_local(actor_input: dict) -> list[dict]:257 """Équivalent local de _run_actor (Apify) : mêmes items, même contrat."""258 return asyncio.run(_amain(actor_input))259