SPB Git

Repository Public

imvest.py 10.2 KB 253 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/imvest.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/imvest.py : connecteur Société Imvest (societeimvest.ca)91#   Le Méribel, 195 logements en 2 phases au 1191, rue de Courchevel à Lévis92#   (secteur Saint-Romuald). WordPress (thème TeamPress) avec plans d'étage93#   interactifs : endpoints AJAX POST maison —94#     /ajax/recherche-etage/ (id=immeuble) -> liste des étages (li.Etage)95#     /ajax/load-etage/ (id=étage)         -> <area> par unité (no, type,96#         superficie dans data-tooltip) + JSON `areas` dont fillColor code le97#         statut : cbcbcb = loué, 940723 = réservé, autre = disponible98#     /ajax/recherche-unite/ (id=unité)    -> détail (disponibilité, plan,99#         caractéristiques)100#   Granularité : unité. Pas de prix publié (Tier B).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import json106import re107108from ..schema import Listing, normalize_unit_type109from .base import BaseConnector110111BASE = "https://www.societeimvest.ca"112AJAX_ETAGES = f"{BASE}/ajax/recherche-etage/"113AJAX_PLAN = f"{BASE}/ajax/load-etage/"114AJAX_UNITE = f"{BASE}/ajax/recherche-unite/"115116# phases (slug de page « immeubles ») — l'id AJAX est lu sur la page117PHASES = [("le-meribel", "Le Méribel — Phase 1"),118          ("le-meribel-phase-2", "Le Méribel — Phase 2")]119120ADDRESS = "1191, rue de Courchevel, Lévis"121LAT, LNG = 46.732973, -71.262941122123IMMEUBLE_ID_RE = re.compile(r"immeuble_id = '(\d+)'")124FLOOR_RE = re.compile(r'<li id="(\d+)" class="Etage"><a class="BoutonEtage"'125                      r' href="#" title="([^"]*)"')126AREA_RE = re.compile(r'<area data-tooltip="([^"]*)" id="(\d+)"[^>]*'127                     r'data-key="(\d+)"')128AREAS_JSON_RE = re.compile(r"areas:\s*(\[.*?\])", re.S)129TYPE_RE = re.compile(r"<strong>([^<]*)</strong>")130SQFT_RE = re.compile(r"Superficie\s*:\s*([\d\s]+)\s*p\.?c\.?", re.I)131DISPO_RE = re.compile(r"Disponibilit[^:]*:\s*<span class=\"Spacing\">"132                      r"([^<]*)</span>", re.I)133PLAN_RE = re.compile(r'href="(https://www\.societeimvest\.ca/wp-content/'134                     r'uploads/[^"]+\.pdf)"')135IMG_RE = re.compile(r'<img[^>]+src="([^"]+phpThumb[^"]+)"')136CARAC_RE = re.compile(r"Caractéristiques du logement</h3>\s*<ul>(.*?)</ul>",137                      re.S)138LI_RE = re.compile(r"<li>(.*?)</li>", re.S)139140# statuts non offerts en location (gris = loué, rouge foncé = réservé)141TAKEN_COLORS = {"cbcbcb", "940723"}142143144class ImvestConnector(BaseConnector):145    source_id = "imvest"146    request_delay = 0.6147148    def fetch(self) -> list[Listing]:149        listings: list[Listing] = []150        for slug, phase_name in PHASES:151            page_url = f"{BASE}/immeubles/{slug}/"152            try:153                page = self.get(page_url).text154            except Exception:155                continue156            m = IMMEUBLE_ID_RE.search(page)157            if not m:158                continue159            try:160                floors_html = self.post(AJAX_ETAGES,161                                        data={"id": m.group(1)}).text162            except Exception:163                continue164            for floor_id, floor_name in FLOOR_RE.findall(floors_html):165                try:166                    listings.extend(self._parse_floor(167                        slug, phase_name, page_url, floor_id, floor_name))168                except Exception:169                    continue170        return listings171172    def _parse_floor(self, slug: str, phase_name: str, page_url: str,173                     floor_id: str, floor_name: str) -> list[Listing]:174        out: list[Listing] = []175        plan_html = self.post(AJAX_PLAN, data={"id": floor_id}).text176177        # statut de chaque unité (JSON mapster : key = no d'unité)178        status: dict[str, str] = {}179        m = AREAS_JSON_RE.search(plan_html)180        if m:181            try:182                for a in json.loads(m.group(1)):183                    status[str(a.get("key"))] = a.get("fillColor", "")184            except ValueError:185                pass186187        for tooltip, unit_id, unit_no in AREA_RE.findall(plan_html):188            color = status.get(unit_no, "")189            if not color or color.lower() in TAKEN_COLORS:190                continue           # loué / réservé / inconnu191192            tm = TYPE_RE.search(tooltip)193            unit_type = normalize_unit_type(tm.group(1)) if tm else ""194            sm = SQFT_RE.search(tooltip)195            area = float(sm.group(1).replace(" ", "").replace(" ", "")) \196                if sm else None197198            key = hashlib.sha1(f"{color}|{tooltip}".encode()).hexdigest()199            d = self.detail(f"{slug}-{unit_no}", key,200                            lambda uid=unit_id: self._fetch_unit(uid))201202            out.append(Listing(203                source=self.source_id,204                external_id=f"{slug}-{unit_no}",205                url=page_url,206                title=f"Unité {unit_no} — {phase_name}",207                address=ADDRESS,208                sector="Saint-Romuald",209                city="Lévis",210                unit_type=unit_type,211                area_sqft=area,212                price_label="Prix sur demande",213                availability=d.get("availability", ""),214                description=f"Unité {unit_no} ({unit_type}), {floor_name} — "215                            f"{phase_name}, Société Imvest, Lévis.",216                amenities=d.get("amenities") or [],217                details={"floor": floor_name,218                         **({"floor_plan": d["plan"]} if d.get("plan")219                            else {})},220                images=d.get("images") or [],221                lat=LAT,222                lng=LNG,223            ))224        return out225226    def _fetch_unit(self, unit_id: str) -> dict:227        """Détail d'une unité via /ajax/recherche-unite/ (POST id=…)."""228        out: dict = {}229        try:230            html = self.post(AJAX_UNITE, data={"id": unit_id}).text231        except Exception:232            return out233        m = DISPO_RE.search(html)234        if m:235            dispo = m.group(1).strip()236            out["availability"] = dispo if re.match(r"^\d|^libre|^immédiat",237                                                    dispo, re.I) \238                else f"Disponibilité : {dispo}"239        m = PLAN_RE.search(html)240        if m:241            out["plan"] = m.group(1)242        m = CARAC_RE.search(html)243        if m:244            out["amenities"] = [245                re.sub(r"<[^>]+>", "", li).strip()246                for li in LI_RE.findall(m.group(1))247                if re.sub(r"<[^>]+>", "", li).strip()][:20]248        imgs = [u.replace("&amp;", "&") for u in IMG_RE.findall(html)249                if "ajax_loading" not in u]250        if imgs:251            out["images"] = imgs[:5]252        return out253
Files main
Menu

Theme