SPB Git

Repository Public

immostar.py 21.9 KB 489 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immostar.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/immostar.py : connecteur Immostar (immostar.ca / immostaralouer.ca)91#   Le résidentiel d'Immostar vit sur un micro-site par projet :92#     - MU (habitermu.ca) et Le Huppé (lehuppe.ca)      -> JSON `var fiches`93#     - Kwayaweh (kwayaweh.ca)                          -> SVG + REST do-selecteur94#     - Le 1070 Cap-Rouge (le1070.ca)                   -> SVG + REST do-selecteur95#     - Le Maguire (lemaguire.ca)                       -> cartes .fiche_unite96#     - Loges Saint-Nicolas (loges.ca, Lévis)           -> cartes .fiche_unite97#   Tous les micro-sites partagent la même plateforme : les pages98#   /aires-de-vie/ et /votre-espace/ listent les commodités du projet.99#   Exclus : Alo Ste-Foy (livraison 2028, rien à louer), Le Florent100#   (Trois-Rivières, hors région Québec/Lévis), immostaralouer.ca (commercial).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import json106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, infer_city, parse_area_sqft, parse_price111from .base import BaseConnector112113_IMG_RE = re.compile(114    r'https?://[^"\'\s\)]+/wp-content/uploads/[^"\'\s\)]+\.(?:jpg|jpeg|webp)',115    re.I)116_SKIP_IMG = re.compile(117    r"logo|icon|favicon|plan|selecteur|niveau-|-\d{2,3}x\d{2,3}\.", re.I)118119120def _type_to_demi(raw: str) -> str:121    """'2 chambres (+ bureau)' -> '4½', 'Studio' -> 'Studio'."""122    s = (raw or "").strip().lower()123    if not s:124        return ""125    if "studio" in s:126        return "Studio"127    if "maison" in s or s.startswith("mdv"):128        return "Maison"129    m = re.search(r"(\d)\s*ch", s)130    if m:131        return f"{int(m.group(1)) + 2}½"132    m = re.search(r"(\d)\s*(?:½|1/2)", s)133    if m:134        return f"{m.group(1)}½"135    return raw.strip()136137138class ImmostarConnector(BaseConnector):139    source_id = "immostar"140    request_delay = 0.6141    max_images = 15142    max_rest_units = 60          # garde-fou REST (le1070)143144    # -- helpers ---------------------------------------------------------------145    def _site_images(self, url: str) -> list[str]:146        try:147            html = self.get(url).text148        except Exception:149            return []150        imgs = [u for u in dict.fromkeys(_IMG_RE.findall(html))151                if not _SKIP_IMG.search(u)]152        return imgs[: self.max_images]153154    def _site_amenities(self, site: str) -> list[str]:155        """Commodités du projet : listes à puces des pages /aires-de-vie/ et156        /votre-espace/ (plateforme commune aux micro-sites Immostar), sinon157        /le-projet/ (Le Maguire). Les <li> contenant des liens (menus,158        pieds de page) sont ignorés."""159        items: list[str] = []160        for page in ("aires-de-vie/", "votre-espace/", "le-projet/"):161            if items and page == "le-projet/":162                break                    # page de repli seulement163            try:164                html = self.get(site + page).text165            except Exception:166                continue167            soup = BeautifulSoup(html, "html.parser")168            for ul in soup.find_all("ul"):169                if ul.find_parent(("nav", "header", "footer")):170                    continue171                cls = " ".join(ul.get("class") or []) + " " + (ul.get("id") or "")172                if re.search(r"menu|nav|footer|cookie", cls, re.I):173                    continue174                for li in ul.find_all("li"):175                    if li.find("a"):176                        continue177                    t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))178                    t = t.lstrip("—-– ").strip()179                    if 3 <= len(t) <= 90 and t not in items:180                        items.append(t)181            # variante Loges : info-boxes WPBakery (h3.aio-icon-title)182            for h3 in soup.select("h3.aio-icon-title"):183                t = re.sub(r"\s+", " ", h3.get_text(" ", strip=True))184                if 3 <= len(t) <= 90 and t not in items:185                    items.append(t)186        return items[:30]187188    @staticmethod189    def _fiches(html: str) -> list[dict]:190        """Extrait `var fiches = {"data": {...}}` (plateforme MU / Le Huppé)."""191        i = html.find("var fiches = ")192        if i < 0:193            return []194        try:195            data, _ = json.JSONDecoder().raw_decode(html[i + len("var fiches = "):])196        except Exception:197            return []198        return list((data.get("data") or {}).values())199200    def _mk(self, proj: dict, num: str, unit_type_raw: str, price_label: str,201            availability: str, desc: str, images: list[str],202            area_sqft: float | None = None, title_num: str = "") -> Listing:203        sector = proj["sector"]204        return Listing(205            source=self.source_id,206            external_id=f"{proj['id']}-{num}",207            url=f"{proj['plans'][0]}#unite-{num}",208            title=f"{proj['name']} — Unité {title_num or num}",209            address=proj.get("address", ""),210            sector=sector,211            city=infer_city(sector),212            unit_type=_type_to_demi(unit_type_raw),213            price=parse_price(price_label),214            price_label=price_label,215            availability=availability,216            area_sqft=area_sqft,217            description=desc[:600],218            amenities=list(proj.get("amenities", [])),219            images=images,220        )221222    @staticmethod223    def _sqft(raw) -> float | None:224        """'630' / '1 102' -> pi² (None si absent ou implausible)."""225        s = str(raw or "").strip().replace(" ", "").replace(",", ".")226        try:227            v = float(s)228        except ValueError:229            return None230        return v if 80 <= v <= 20000 else None231232    # -- parseurs par plateforme ------------------------------------------------233    def _parse_fiches(self, proj: dict, html: str,234                      images: list[str]) -> list[Listing]:235        out = []236        for f in self._fiches(html):237            dispo = f.get("disponibilite")238            if isinstance(dispo, dict):        # variante MU239                dispo = dispo.get("value")240            if dispo != "available":241                continue242            num = str(f.get("numero") or "").strip()243            if not num:244                continue245            t = f.get("type") or ""246            if isinstance(t, dict):            # variante MU247                t = t.get("label", "")248            if str(f.get("bureau")) == "1":249                t += " + bureau"250            prix = str(f.get("prix") or "").strip()251            sup = str(f.get("superficie") or "").strip()252            terrasse = str(f.get("superficie_terrasse") or "").strip()253            chambres = str(f.get("chambres") or "").strip()254            sdb = str(f.get("salles_de_bain") or "").strip()255            caract = str(f.get("caracteristiques") or "").strip()256            desc = " — ".join(x for x in [257                t, f"{sup} pi²" if sup else "",258                f"terrasse {terrasse} pi²" if terrasse else "",259                f"{chambres} chambre(s)" if chambres else "",260                f"{sdb} salle(s) de bain" if sdb else "",261                caract if caract and caract.lower() != "regulier" else "",262                f"étage {f.get('etage')}" if f.get("etage") else ""] if x)263            # plan de l'unité en tête de galerie (si image, pas PDF)264            imgs = list(images)265            plan = str(f.get("plan") or "")266            if re.search(r"\.(?:jpe?g|png|webp)$", plan, re.I):267                imgs.insert(0, plan)268            out.append(self._mk(269                proj, num, t,270                f"{prix}$ / mois" if prix else "",271                f"Libre {f['date']}" if f.get("date") else "Disponible",272                desc, imgs, area_sqft=self._sqft(sup)))273        return out274275    def _parse_do_rest(self, proj: dict, html: str,276                       images: list[str]) -> list[Listing]:277        """Kwayaweh / Le 1070 : éléments SVG `disponible` data-numero= + REST278        /wp-json/do-selecteur-plans/v1/unite?id=N (prix, superficie, type,279        date de libération, plan). Les éléments Kwayaweh portent280        data-prix/type/promotion : cette carte sert de clé de cache BD281        (self.detail) pour ne re-frapper le REST que si l'unité a changé."""282        base = re.match(r"https?://[^/]+", proj["plans"][0]).group(0)283        soup = BeautifulSoup(html, "html.parser")284        cards: list[tuple[str, dict]] = []285        seen: set[str] = set()286        for el in soup.select("[data-numero]"):287            cls = " ".join(el.get("class") or [])288            if not re.search(r"\b(disponible|available)\b", cls) \289                    or "indisponible" in cls:290                continue291            num = (el.get("data-numero") or "").strip()292            if not num or num in seen:293                continue294            seen.add(num)295            attrs = {k: str(v) for k, v in el.attrs.items()296                     if k.startswith("data-")}297            attrs["class"] = cls298            cards.append((num, attrs))299300        uid_from_numero = proj.get("uid_field") == "numero"301        out = []302        for num, attrs in cards[: self.max_rest_units]:303            def _fetch(n=num):304                if self._rest_fetched >= self.max_rest_units * 2:305                    raise RuntimeError("budget de requêtes REST atteint")306                self._rest_fetched += 1307                return self.get(308                    f"{base}/wp-json/do-selecteur-plans/v1/unite",309                    params={"id": n}).json()310            try:311                if uid_from_numero and "data-prix" in attrs:312                    # uid connu d'avance -> cache BD (clé = attributs SVG)313                    key = hashlib.sha1(json.dumps(314                        attrs, sort_keys=True).encode()).hexdigest()[:20]315                    data = self.detail(f"{proj['id']}-{num}", key, _fetch)316                else:317                    data = _fetch()318            except Exception:319                continue320            if not data or data.get("etat") != "disponible":321                continue322            unite = str(data.get("unite") or num)323            t = str(data.get("type") or "")324            sup = str(data.get("superficie_habitable") or "").strip()325            terrasse = str(data.get("superficie_terrasse") or "").strip()326            chambres = str(data.get("nb_chambres") or "").strip()327            style = str(data.get("style") or "").strip()328            parking = str(data.get("stationnement") or "").strip()329            desc = " — ".join(x for x in [330                t, f"{sup} pi²" if sup else "",331                f"terrasse {terrasse} pi²" if terrasse else "",332                f"{chambres} chambre(s)" if chambres else "",333                style,334                f"stationnement {parking}" if parking else "",335                f"étage {attrs.get('data-etage')}"336                if attrs.get("data-etage") else ""] if x)337            date_libre = str(data.get("date_libre") or "").strip()338            a_partir = str(data.get("a_partir") or "").strip()339            avail = (f"Libre {date_libre}" if date_libre340                     else a_partir or "Disponible")341            imgs = list(images)342            for g in (data.get("gallery") or []):343                gu = g.get("url") if isinstance(g, dict) else str(g or "")344                if gu and gu.startswith("http") and gu not in imgs:345                    imgs.insert(0, gu)346            montant = str(data.get("montant") or "").strip()347            out.append(self._mk(348                proj, num if uid_from_numero else unite,349                t or str(data.get("type_demi") or ""),350                f"À partir de {montant}" if montant else "",351                avail, desc, imgs,352                area_sqft=self._sqft(sup), title_num=unite))353        return out354355    def _parse_maguire(self, proj: dict, html: str,356                       images: list[str]) -> list[Listing]:357        """Le Maguire : cartes `.fiche_unite.available` rendues serveur358        (prix, superficies, chambres, plan JPG de l'unité)."""359        soup = BeautifulSoup(html, "html.parser")360        out = []361        for card in soup.select(".fiche_unite"):362            cls = card.get("class") or []363            if "available" not in cls or "rented" in cls:364                continue365            num = (card.get("data-unite") or "").strip()366            if not num:367                continue368            prix_el = card.select_one(".prix")369            price_label = prix_el.get_text(" ", strip=True) if prix_el else ""370            sup_el = card.select_one("p.superficie:not(.terrasse)")371            sup_txt = sup_el.get_text(" ", strip=True) if sup_el else ""372            terr_el = card.select_one("p.superficie.terrasse")373            terr_txt = terr_el.get_text(" ", strip=True) if terr_el else ""374            notes_el = card.select_one(".notes")375            t = notes_el.get_text(" ", strip=True) if notes_el else ""376            dispo = card.select_one(".disponibilite")377            etage = (card.get("data-etage") or "").strip()378            desc = " — ".join(x for x in [379                t, sup_txt, terr_txt,380                f"étage {etage}" if etage else ""] if x)381            imgs = list(images)382            plan = card.select_one("a.pdf[href]")383            if plan and re.search(r"\.(?:jpe?g|png|webp)$",384                                  plan.get("href") or "", re.I):385                imgs.insert(0, plan["href"])386            out.append(self._mk(387                proj, num, t, price_label,388                dispo.get_text(strip=True) if dispo else "Disponible",389                desc, imgs, area_sqft=parse_area_sqft(sup_txt)))390        return out391392    def _parse_loges(self, proj: dict, html: str,393                     images: list[str]) -> list[Listing]:394        """Loges : cartes `.affichage.liste .fiche_unite` rendues serveur."""395        soup = BeautifulSoup(html, "html.parser")396        out = []397        for card in soup.select(".affichage.liste .fiche_unite"):398            num = (card.get("data-unite") or "").strip()399            h4 = card.select_one("h4")400            head = h4.get_text(" ", strip=True) if h4 else ""401            if not num or "$" not in head:402                continue  # unité louée ou sans prix403            info = card.select_one("header p")404            info_txt = info.get_text(" ", strip=True) if info else ""405            m = re.search(r"(\d)\s*chambre", info_txt)406            t = f"{m.group(1)} chambres" if m else ""407            dispo = card.select_one(".disponibilite")408            desc_el = card.select_one("main .description")409            desc_txt = (re.sub(r"\s+", " ", desc_el.get_text(" ", strip=True))410                        if desc_el else "")411            desc = " — ".join(x for x in [info_txt, desc_txt] if x)412            price_m = re.search(r"À partir de\s*([\d\s,.]+\$)", head)413            price_label = (f"À partir de {price_m.group(1)}/mois"414                           if price_m else head)415            out.append(self._mk(416                proj, num, t, price_label,417                dispo.get_text(strip=True) if dispo else "Disponible",418                desc, images, area_sqft=parse_area_sqft(info_txt)))419        return out420421    # -- fetch -----------------------------------------------------------------422    def fetch(self) -> list[Listing]:423        projects = [424            {"id": "mu", "name": "MU", "sector": "Sainte-Foy",425             "address": "2605, boulevard Laurier, Québec",426             "site": "https://habitermu.ca/",427             "plans": ["https://habitermu.ca/plans/"], "mode": "fiches"},428            {"id": "huppe", "name": "Le Huppé", "sector": "Lebourgneuf",429             "address": "5055, boulevard des Gradins, Québec",430             "site": "https://lehuppe.ca/",431             "plans": ["https://lehuppe.ca/plans/"], "mode": "fiches"},432            {"id": "1070", "name": "Le 1070 Cap-Rouge", "sector": "Cap-Rouge",433             "address": "1070, boulevard de la Chaudière, Québec",434             "site": "https://le1070.ca/",435             "plans": ["https://le1070.ca/plans/"], "mode": "do_rest"},436            {"id": "kwayaweh", "name": "Kwayaweh", "sector": "Wendake",437             "address": "Wendake",438             "site": "https://kwayaweh.ca/",439             "plans": ["https://kwayaweh.ca/selecteur/"], "mode": "do_rest",440             "uid_field": "numero"},   # uid historique = data-numero (post id)441            {"id": "maguire", "name": "Le Maguire sur l'avenue",442             "sector": "Sillery", "address": "Avenue Maguire, Québec",443             "site": "https://lemaguire.ca/",444             "plans": ["https://lemaguire.ca/les-plans/"], "mode": "maguire"},445            {"id": "loges-555", "name": "Loges Saint-Nicolas (Le 555)",446             "sector": "Saint-Nicolas", "address": "555, rue Marie-Victorin, Lévis",447             "site": "https://loges.ca/",448             "plans": ["https://loges.ca/plans/le-555/"], "mode": "loges"},449            {"id": "loges-550", "name": "Loges Saint-Nicolas (Le 550)",450             "sector": "Saint-Nicolas", "address": "550, rue Jérôme-Demers, Lévis",451             "site": "https://loges.ca/",452             "plans": ["https://loges.ca/plans/le-550/"], "mode": "loges"},453            {"id": "loges-600", "name": "Loges Saint-Nicolas (Le 600)",454             "sector": "Saint-Nicolas", "address": "600, rue Pierre-Perrault, Lévis",455             "site": "https://loges.ca/",456             "plans": ["https://loges.ca/plans/le-600/"], "mode": "loges"},457        ]458        parsers = {459            "fiches": self._parse_fiches,460            "do_rest": self._parse_do_rest,461            "maguire": self._parse_maguire,462            "loges": self._parse_loges,463        }464465        self._rest_fetched = 0466        listings: list[Listing] = []467        site_imgs: dict[str, list[str]] = {}468        site_amen: dict[str, list[str]] = {}469        for proj in projects:470            try:471                site = proj["site"]472                if site not in site_imgs:473                    site_imgs[site] = self._site_images(site)474                if site not in site_amen:475                    site_amen[site] = self._site_amenities(site)476                images = site_imgs[site]477                proj["amenities"] = site_amen[site]478                for plans_url in proj["plans"]:479                    html = self.get(plans_url).text480                    listings.extend(parsers[proj["mode"]](proj, html, images))481            except Exception:482                continue483484        # dédup par external_id (sécurité)485        uniq: dict[str, Listing] = {}486        for lst in listings:487            uniq.setdefault(lst.external_id, lst)488        return list(uniq.values())489
Files main
Menu

Theme