Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/agences_web.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-2513# Last Modified : 2026-08-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 maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/agences_web.py : agences INDÉPENDANTES à site web « classique »91# (WordPress ou CMS immobilier server-rendered). Issu du recensement OACIQ92# 2026-08 : chaque bannière non couverte dont la page des inscriptions expose93# des liens de fiches portant le n° Centris (7-9 chiffres) reçoit SON94# connecteur, généré depuis data/web_agencies.json (un source_id par bannière).95#96# Fonctionnement générique :97# - liste : chaque list_url est lue (pagination via «{page}» au besoin) ; les98# liens de fiches sont extraits par regex (href même domaine contenant un99# n° 7-9 chiffres, ou <loc> si l'URL est un sitemap XML) ;100# - détail : chaque fiche est enrichie (cache BD, _detailutil.enrich) par un101# parseur générique — JSON-LD (Place/Offer/RealEstateListing), tableaux102# Centris aplatis, prix/chambres/sdb par regex, galerie (og:image, CDN103# Centris, fancybox/lightbox), GPS Google Maps.104#105# Ces agences ne sont couvertes par AUCUNE bannière déjà agrégée → fiches106# ADDITIVES, source_id simple (pas d'infixe _ag_). Le n° Centris devient107# l'external_id : vendre_ag_ca (portail, _ag_) se fait masquer ses doublons.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import html as _html112import json113import os114import re115import urllib.parse116from pathlib import Path117118from .base import BaseConnector119from . import _detailutil as du120from ..normalize import normalize_property_type, parse_price121from ..schema import PropertyListing122123REGISTRY = Path(__file__).resolve().parent.parent.parent / "data" / "web_agencies.json"124DETAIL_LIMIT = int(os.environ.get("IMMOKA_WEB_DETAIL_LIMIT",125 os.environ.get("IMMOKA_DETAIL_LIMIT", "150")))126127_HREF_RE = re.compile(r'href="([^"#]+)"', re.I)128# cartes cliquables sans lien <a> (« data-listing-url="/…?code=12345678" »)129_DATA_URL_RE = re.compile(r'data-listing-url="([^"#]+)"', re.I)130# ces cartes portent leurs données en attributs data-* (prix, type, chambres,131# coordonnées, photo) et leur statut en clair (« À vendre » / « À louer »)132_CITY_POSTAL_RE = re.compile(r"\s+([A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d)\s*$")133_CARD_SPLIT_RE = re.compile(r'(?=<div[^>]*\bdata-listing-url=")', re.I)134_CARD_ATTR_RE = re.compile(r'\bdata-([a-z-]+)="([^"]*)"', re.I)135_CARD_RENT_RE = re.compile(r">\s*(?:[ÀA] louer|For rent|Lou[ée]e?|Rented)\s*<|"136 r"/\s*mois|/\s*month|par mois", re.I)137138139def _cards(body: str) -> dict[str, dict]:140 """n° d'inscription → attributs de sa carte (+ `rent` si c'est un loyer)."""141 out: dict[str, dict] = {}142 for seg in _CARD_SPLIT_RE.split(body)[1:]:143 end = seg.find(">")144 attrs = {k.lower(): _html.unescape(v).strip()145 for k, v in _CARD_ATTR_RE.findall(seg[:end if end > 0 else 2000])}146 m = _ID_RE.search(attrs.get("listing-url", "")) or _ID_RE.search(attrs.get("mls", ""))147 if not m:148 continue149 # le statut précède le n° MLS dans la carte ; on ne lit pas au-delà150 # (le reste de la page peut contenir un lien « À louer » sans rapport)151 stop = seg.find("MLS#")152 zone = seg[:stop if stop > 0 else 8000] + " " + attrs.get("price", "")153 attrs["rent"] = bool(_CARD_RENT_RE.search(zone))154 out[m.group(1)] = attrs155 return out156157158def _apply_card(lst: PropertyListing, c: dict) -> None:159 """Données fiables de la carte : elles priment sur le parseur de fiche160 générique (apply_detail n'écrase jamais un champ déjà rempli)."""161 label = (c.get("price") or "").strip()162 price = parse_price(label)163 if price:164 lst.price, lst.price_label = price, label165 ptype = normalize_property_type(c.get("property-type") or "")166 if ptype in _CANON_TYPES:167 lst.property_type = ptype168 for field, key in (("bedrooms", "bedrooms"), ("bathrooms", "bathrooms")):169 v = (c.get(key) or "").strip()170 if v.isdigit():171 setattr(lst, field, int(v))172 # caractéristiques affichées sur la carte (faits de la source, tels quels)173 for key, one, many in (("bedrooms", "chambre", "chambres"),174 ("bathrooms", "salle de bain", "salles de bain"),175 ("rooms", "pièce", "pièces")):176 v = (c.get(key) or "").strip()177 if v.isdigit() and int(v) > 0:178 lst.features.append(f"{v} {one if v == '1' else many}")179 try:180 lat, lng = float(c.get("lat") or ""), float(c.get("lng") or "")181 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:182 lst.lat, lst.lng = lat, lng183 except ValueError:184 pass185 img = c.get("image") or ""186 if img.startswith("http") and img not in lst.images:187 lst.images.insert(0, img)188_LOC_RE = re.compile(r"<loc>([^<]+)</loc>")189_ID_RE = re.compile(r"(?<!\d)(\d{7,9})(?!\d)")190# jamais des fiches : assets, réseaux sociaux, flux, plugins191_JUNK = ("wp-content", "wp-json", "wp-includes", "facebook.", "instagram.",192 "linkedin.", "twitter.", "youtube.", "fonts.", "squarespace",193 "iubenda", "gravatar", "cdn-cgi", "mailto:", "tel:", "/feed",194 "javascript:", "google.", "centris.ca", "realtor.ca", ".css", ".js",195 ".jpg", ".jpeg", ".png", ".webp", ".svg", ".gif", ".pdf", ".ico",196 ".xml", "?share=", "replytocom")197_SOLD = ("vendu", "sold", "-loue", "/loue", "a-louer", "for-rent", "rented")198199_PRICE_RE = re.compile(r"(\d{1,3}(?:[ \u00a0\u202f\u2009,]\d{3})+(?:[.,]\d{2})?)\s*\$"200 r"|\$\s?(\d{1,3}(?:,\d{3})+)")201_BEDS_RE = re.compile(r"(\d{1,2})\s*(?:chambre|cac\b|bedroom|beds?\b)", re.I)202_BATHS_RE = re.compile(r"(\d{1,2})\s*(?:salle[s]?\s*de\s*bain|sdb\b|bathroom|baths?\b)", re.I)203_OG_RE = re.compile(r'property="og:image"\s+content="([^"]+)"|'204 r'content="([^"]+)"\s+property="og:image"', re.I)205_CENTRIS_IMG_RE = re.compile(r'https?://mspublic\.centris\.ca/media\.ashx\?[^"\'\\ ]+', re.I)206_GALLERY_RE = re.compile(r'(?:data-(?:fancybox|lightbox|src)|data-full)="'207 r'(https?://[^"]+\.(?:jpe?g|png|webp)[^"]*)"', re.I)208_LD_IMG_TYPES = {"RealEstateListing", "Product", "Residence", "House",209 "SingleFamilyResidence", "Apartment", "Accommodation", "Place"}210_META_DESC_RE = re.compile(r'<meta\s+(?:name="description"|property="og:description")\s+'211 r'content="([^"]{40,})"', re.I)212_H1_RE = re.compile(r"<h1[^>]*>(.*?)</h1>", re.I | re.S)213_TAG_RE = re.compile(r"<[^>]+>")214_REL_IMG_RE = re.compile(r'<img[^>]+src="(/[^"]+\.(?:jpe?g|png|webp)[^"]*)"', re.I)215_POSTAL_RE = re.compile(r"^[A-Z]\d[A-Z]\s?\d[A-Z]\d$")216_TITLE_RE = re.compile(r"<title>(.*?)</title>", re.I | re.S)217# « Candiac, QC », « Laval (Chomedey), Québec »218_CITY_QC_RE = re.compile(r"([A-ZÀ-Ü][\w'’.() \-]{2,40}),\s*(?:QC\b|Québec)")219# <title> « À vendre — Montréal (Mercier) | Agence »220_VENDRE_CITY_RE = re.compile(r"[àa] vendre\s*[—–:-]\s*([A-ZÀ-Ü][^|<>{}]{2,50}?)"221 r"\s*(?:\||$)", re.I)222# texte aplati : « Description | {paragraphe} »223_DESC_FLAT_RE = re.compile(r"(?:Description(?: de la propriété)?|"224 r"À propos de cette propriété)\s*\|\s*([^|]{60,})", re.I)225# jamais une ville : libellés de voie (l'adresse déborde parfois dans le titre)226_STREET_RE = re.compile(r"(?:rue|route|rte|ch\.?|chemin|boul\.?|boulevard|"227 r"av\.?|avenue|rang|montée|croissant|impasse|place)\s",228 re.I)229# seuls les types canoniques d'Immo-Ka sont retenus (normalize_property_type230# renvoie le texte capitalisé quand rien ne matche — on l'écarte)231_CANON_TYPES = {"Maison", "Maison mobile", "Jumelé", "Maison de ville", "Condo",232 "Duplex", "Triplex", "Multiplex", "Chalet", "Terrain",233 "Fermette/Agricole", "Commercial"}234235236class _AgenceWeb(BaseConnector):237 """Connecteur générique d'agence à site server-rendered (voir registre)."""238239 agency_name = ""240 site_url = ""241 list_urls: list[str] = []242 require = "" # sous-chaîne obligatoire dans l'URL de fiche243 render = False # fiches JS (Next.js…) : détail via Scrapfly244 max_pages = 30245 request_delay = 0.5246247 def fetch(self) -> list[PropertyListing]:248 by_id: dict[str, PropertyListing] = {}249 for tpl in self.list_urls:250 if "{page}" in tpl:251 dry = 0252 for page in range(1, self.max_pages + 1):253 before = len(by_id)254 if not self._collect(tpl.format(page=page), by_id):255 break256 dry = dry + 1 if len(by_id) == before else 0257 if dry >= 2:258 break259 else:260 self._collect(tpl, by_id)261 listings = list(by_id.values())262263 def fetch_html(u: str) -> str:264 h = self.get_scrapfly(u, rendering_wait=3000) if self.render \265 else self.get(u).text266 # marqueur pour que le parseur puisse absolutiser les URLs relatives267 return h + f"\n<!--immoka-url {u}-->"268269 du.enrich(self, listings, DETAIL_LIMIT, parse_web_detail, key="v3",270 fetch_html=fetch_html)271 # code postal collé à la ville (« Montréal (Ville-Marie) H3B 9A9 ») :272 # il va dans details.postal_code, la ville reste une ville273 for lst in listings:274 m = _CITY_POSTAL_RE.search(lst.city or "")275 if m:276 lst.details.setdefault("postal_code", m.group(1).upper())277 lst.city = lst.city[:m.start()].rstrip(" ,")278 # une « description » identique sur plusieurs fiches est le texte279 # générique du site (meta description), pas celle de la propriété280 seen: dict[str, int] = {}281 for lst in listings:282 if lst.description:283 seen[lst.description] = seen.get(lst.description, 0) + 1284 for lst in listings:285 if lst.description and seen[lst.description] >= 3:286 lst.description = ""287 # les loyers (« … $ par mois ») ne sont pas des maisons à vendre288 listings = [l for l in listings289 if not (l.price is None and "par mois" in (l.price_label or ""))]290 for lst in listings:291 if not lst.title:292 lst.title = lst.address or _title_from_slug(lst.url) \293 or "Propriété à vendre"294 return listings295296 def _collect(self, url: str, by_id: dict) -> bool:297 try:298 body = self.get(url).text299 except Exception:300 return False301 # pagination AJAX : réponse JSON {"html": "<cartes…>"} → on lit le HTML302 if body.lstrip().startswith("{"):303 try:304 body = json.loads(body).get("html") or body305 except (ValueError, AttributeError):306 pass307 host = urllib.parse.urlparse(self.site_url).netloc.lower().removeprefix("www.")308 # certains CMS déclarent <base href> : les liens relatifs partent de là309 mb = re.search(r'<base\s+href="([^"]+)"', body[:6000], re.I)310 base = mb.group(1) if mb else url311 raw = _LOC_RE.findall(body) if "<loc>" in body[:4000] or url.endswith(".xml") \312 else _HREF_RE.findall(body) + _DATA_URL_RE.findall(body)313 cards = _cards(body) if "data-listing-url" in body else {}314 for href in raw:315 href = _html.unescape(href)316 low = href.lower()317 if any(j in low for j in _JUNK) or any(s in low for s in _SOLD):318 continue319 m = _ID_RE.search(href)320 if not m:321 continue322 absu = urllib.parse.urljoin(base, href)323 h = urllib.parse.urlparse(absu).netloc.lower().removeprefix("www.")324 if h != host:325 continue326 if self.require and self.require not in absu.lower():327 continue328 eid = m.group(1)329 card = cards.get(eid) or {}330 if card.get("rent"):331 # loyer : Immo-Ka ne publie que des biens à vendre332 by_id.pop(eid, None)333 continue334 if eid not in by_id:335 by_id[eid] = PropertyListing(336 source=self.source_id, external_id=eid, url=absu,337 mls=eid, agency=self.agency_name, broker_name=self.agency_name)338 if card:339 _apply_card(by_id[eid], card)340 return True341342343def _title_from_slug(url: str) -> str:344 """« …/triplex-a-vendre-longueuil-st-hubert-15180332-detail-Fr » → titre."""345 stop = {"details", "detail", "proprietes", "propriete", "properties",346 "property", "listings", "listing", "inscriptions", "fiche",347 "fr", "en", "index"}348 segs = [s for s in urllib.parse.urlparse(url).path.split("/") if s]349 words: list[str] = []350 for seg in reversed(segs):351 seg = urllib.parse.unquote_plus(seg)352 seg = re.sub(r"\.(?:html?|php|aspx?)$", "", seg, flags=re.I)353 seg = re.sub(r"\d{7,9}", " ", seg)354 seg = re.sub(r"detail-?fr", " ", seg, flags=re.I)355 words = [w for w in seg.replace("_", "-").replace(" ", "-").split("-") if w]356 if words and not all(w.lower() in stop for w in words):357 break358 words = []359 if not words:360 return ""361 txt = " ".join(words)362 txt = re.sub(r"\ba vendre\b", "à vendre", txt, flags=re.I)363 txt = re.sub(r"\ba louer\b", "à louer", txt, flags=re.I)364 return (txt[:1].upper() + txt[1:])[:120]365366367# --- parseur détail générique -------------------------------------------------368_RENT_TAIL_RE = re.compile(r"\s*(?:\+\s*tx\s*)?(?:par mois|/\s*mois|/\s*month|"369 r"month|mensuel|par semaine|par nuit)", re.I)370# queues qui trahissent un filtre de recherche, une plage ou une évaluation/taxe371_JUNK_TAIL_RE = re.compile(r"\s*(?:et (?:moins|plus)|-\s*\d|à\s*\d|\(20\d\d\))", re.I)372# contextes boilerplate (calculatrice hypothécaire, plages de filtres)373_JUNK_CTX = ("de plus de", "supérieure à", "inférieure à", "mise de fond",374 "more than", "down payment", "valeur de")375_ASKED_RE = re.compile(r"prix demandé", re.I)376377378def _pick_price(flat: str, out: dict) -> None:379 """Choisit le prix de vente dans le texte aplati ; marque les locations380 (« … $ par mois ») via price_label sans prix — la fiche sera écartée."""381 candidates = []382 rent_label = ""383 for m in _PRICE_RE.finditer(flat):384 raw = (m.group(1) or m.group(2))385 try:386 val = float(re.sub(r"[^\d.]", "", raw.replace(",", ""))[:12])387 except ValueError:388 continue389 tail = flat[m.end():m.end() + 16]390 if _RENT_TAIL_RE.match(tail):391 # loyer — la fiche peut aussi être à vendre : on continue à chercher392 rent_label = rent_label or (m.group(0).strip() + " par mois")393 continue394 if _JUNK_TAIL_RE.match(tail):395 continue396 ctx = flat[max(0, m.start() - 70):m.start()]397 if ctx.rstrip().endswith("-") or any(w in ctx.lower() for w in _JUNK_CTX):398 continue399 if 25_000 <= val <= 100_000_000:400 labeled = bool(_ASKED_RE.search(ctx[-30:]))401 candidates.append((labeled, val, m.group(0).strip()))402 if labeled:403 break404 if candidates:405 # « Prix demandé » bat le premier montant venu (évaluations, comparables…)406 candidates.sort(key=lambda c: not c[0])407 _, val, label = candidates[0]408 out["price"], out["price_label"] = val, label409 elif rent_label:410 # uniquement un loyer : fiche en location (écartée par le connecteur)411 out["price_label"] = rent_label412413414def parse_web_detail(html: str) -> dict:415 """Fiche server-rendered générique : JSON-LD, tableaux Centris, regex."""416 out: dict = {}417 details: dict = {}418419 # JSON-LD (adresse, géo, prix, description, images)420 imgs: list[str] = []421 for n in du.ld_nodes(html):422 t = n.get("@type")423 types = set(t if isinstance(t, list) else [t])424 if not (types & _LD_IMG_TYPES) and "Offer" not in types:425 continue426 addr = n.get("address")427 if isinstance(addr, dict):428 if addr.get("streetAddress"):429 st = str(addr["streetAddress"]).strip().lstrip(", ").strip()430 if st:431 out.setdefault("address", st)432 if addr.get("addressLocality"):433 loc = str(addr["addressLocality"]).strip()434 # certains sites mettent le code postal dans la localité435 if _POSTAL_RE.match(loc.upper()):436 details.setdefault("postal_code", loc)437 elif loc:438 out.setdefault("city", loc)439 if addr.get("postalCode"):440 details.setdefault("postal_code", str(addr["postalCode"]))441 geo = n.get("geo") or {}442 if isinstance(geo, dict):443 try:444 lat, lng = float(geo["latitude"]), float(geo["longitude"])445 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:446 out.setdefault("lat", lat), out.setdefault("lng", lng)447 except (KeyError, TypeError, ValueError):448 pass449 offers = n.get("offers") or (n if "Offer" in types else {})450 if isinstance(offers, dict) and offers.get("price"):451 try:452 out.setdefault("price", float(str(offers["price"]).replace(",", "")))453 except ValueError:454 pass455 img = n.get("image")456 for u in (img if isinstance(img, list) else [img]):457 if isinstance(u, str) and u.startswith("http"):458 imgs.append(u)459 elif isinstance(u, dict) and u.get("url"):460 imgs.append(u["url"])461 y = n.get("yearBuilt")462 if y and str(y).isdigit():463 out.setdefault("year_built", int(y))464465 desc = du.ld_description(html)466 if not desc:467 md = _META_DESC_RE.search(html)468 if md:469 desc = _html.unescape(md.group(1)).strip()470 if desc:471 out["description"] = desc[:6000]472473 # adresse depuis le <h1> (« 72Z Ch. Valley, Brome ») si le JSON-LD est muet474 if "address" not in out:475 mh = _H1_RE.search(html)476 if mh:477 h1 = _html.unescape(_TAG_RE.sub(" ", mh.group(1)))478 h1 = re.sub(r"\s+", " ", h1).strip().strip(",-– ").strip()479 if 5 <= len(h1) <= 120 and any(c.isdigit() for c in h1) \480 and "$" not in h1:481 parts = [p.strip() for p in h1.split(",") if p.strip()]482 out["address"] = parts[0]483 for p in parts[1:]:484 if _POSTAL_RE.match(p.upper()):485 details.setdefault("postal_code", p)486 else:487 out.setdefault("city", p)488 break489490 # texte aplati : prix, chambres, sdb + tableaux Centris491 flat = du.flatten(html)492 if "price" not in out:493 _pick_price(flat, out)494 mb = _BEDS_RE.search(flat)495 if mb and int(mb.group(1)) <= 19:496 out["bedrooms"] = int(mb.group(1))497 ms = _BATHS_RE.search(flat)498 if ms and int(ms.group(1)) <= 19:499 out["bathrooms"] = int(ms.group(1))500 details.update(du.centris_details(flat))501502 # description encore vide : paragraphe « Description | … » du texte aplati,503 # sinon le plus long segment de prose (≥ 150 caractères, pas de code)504 if len(out.get("description") or "") < 50:505 md = _DESC_FLAT_RE.search(flat)506 if md:507 out["description"] = md.group(1).strip()[:6000]508 else:509 segs = [s.strip() for s in flat.split(" | ")510 if len(s.strip()) >= 150 and "{" not in s511 and s.count(";") < 5 and not any(512 j in s for j in ("function", "var ", "=>",513 "fbq(", "gtag(", "img:", "http"))]514 if segs:515 out["description"] = max(segs, key=len)[:6000]516517 mt = _TITLE_RE.search(html)518 title_txt = _html.unescape(mt.group(1)).strip() if mt else ""519520 # ville : « Candiac, QC » dans le texte > « À vendre — Ville » du <title>521 # > dernier segment « adresse, Ville » du <title>522 if "city" not in out:523 cand = ""524 mc = _CITY_QC_RE.search(flat)525 if mc:526 cand = mc.group(1).strip()527 elif title_txt:528 mv = _VENDRE_CITY_RE.search(title_txt)529 if mv:530 cand = mv.group(1).strip()531 else:532 base = re.split(r"\s*[|–—-]\s*(?=[A-ZÀ-Ü][\w' ]+$)", title_txt)[0]533 if "," in base and "$" not in base:534 cand = base.rsplit(",", 1)[1].strip()535 if (2 <= len(cand) <= 45 and not any(c.isdigit() for c in cand)536 and not _STREET_RE.match(cand)):537 out["city"] = cand538539 # <title> « 179 Prom. St-Louis, Notre-Dame-de-l'Île-Perrot, Montérégie,540 # J7W3J6 » : premier segment sans chiffres après l'adresse = la ville541 if "city" not in out and "," in title_txt:542 seg0 = title_txt.split("|")[0]543 for p in [p.strip() for p in seg0.split(",")][1:]:544 if (2 <= len(p) <= 45 and not any(c.isdigit() for c in p)545 and p[:1].isupper() and not _STREET_RE.match(p)546 and normalize_property_type(p) not in _CANON_TYPES):547 out["city"] = p548 break549550 # type de bien : libellé « Type de propriété | X », slug d'URL551 # (« maison-a-etages/… »), <title>, description552 mu0 = re.search(r"<!--immoka-url (\S+)-->", html[-3000:])553 path = urllib.parse.unquote_plus(554 urllib.parse.urlparse(mu0.group(1)).path) if mu0 else ""555 mtype = re.search(r"Type(?: de propriété| de bien)?\s*\|\s*([^|]{3,40})\s*\|",556 flat, re.I)557 for cand in ((mtype.group(1) if mtype else ""),558 path.replace("-", " ").replace("/", " | "), title_txt,559 (out.get("description") or "")[:300], flat[:300]):560 if not cand:561 continue562 pt = normalize_property_type(cand)563 if pt in _CANON_TYPES:564 out["property_type"] = pt565 break566567 # galerie : fancybox/lightbox > CDN Centris > <img> relatifs > og:image568 gal = list(dict.fromkeys(_GALLERY_RE.findall(html)))569 if not gal:570 gal = list(dict.fromkeys(_CENTRIS_IMG_RE.findall(html)))571 if not gal:572 mu = re.search(r"<!--immoka-url (\S+)-->", html[-3000:])573 if mu:574 rel = [s for s in _REL_IMG_RE.findall(html)575 if not any(j in s.lower() for j in ("logo", "icon", "favicon"))]576 gal = [urllib.parse.urljoin(mu.group(1), s)577 for s in dict.fromkeys(rel)]578 if not gal:579 for a, b in _OG_RE.findall(html):580 u = _html.unescape(a or b)581 if u.startswith("http"):582 gal.append(u)583 if not gal and imgs:584 gal = list(dict.fromkeys(imgs))585 if gal:586 out["images"] = [_html.unescape(u) for u in gal[:80]]587588 if "lat" not in out:589 coords = du.gmaps_coords(html)590 if coords:591 out["lat"], out["lng"] = coords592593 if details:594 out["details"] = details595 return out596597598def _load() -> list[dict]:599 try:600 return json.loads(REGISTRY.read_text(encoding="utf-8"))601 except Exception:602 return []603604605# Génère une classe par agence du registre.606for _ag in _load():607 if not all(_ag.get(k) for k in ("id", "site", "list_urls")):608 continue609 _sid = _ag["id"]610 globals()[f"AGENCE_WEB_{_sid.upper()}"] = type(611 "AgenceWeb" + "".join(p.title() for p in _sid.split("_")),612 (_AgenceWeb,),613 {614 "source_id": _sid,615 "site_url": _ag["site"],616 "list_urls": list(_ag["list_urls"]),617 "agency_name": _ag.get("name", _sid.title()),618 "require": _ag.get("require", ""),619 "render": bool(_ag.get("render")),620 "max_pages": int(_ag.get("max_pages", 30)),621 },622 )623