SPB Git

Repository Public

edifia.py 26.3 KB 603 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/edifia.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# 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/edifia.py : connecteur Edifia Groupe Immobilier (edifiaimmobilier.com)91#   Le locatif d'Edifia est réparti sur plusieurs plateformes :92#     - Le Vital (levitalappartements.com, Lévis/Desjardins, 230 unités)93#         -> sélecteur Livya : la page « Plans et prix » pointe vers un module94#            app.livya.com dont le HTML (Next.js/RSC) embarque le JSON complet95#            des unités (prix, superficie, chambres, étage, date de libération)96#     - Capella (capellalevis.com, Lévis, résidence pour aînés, 198 unités)97#         -> sélecteur d'étages « sysc » : JSON `units = [[...]]` dans la page98#     - Le Cardinal Sud (appartementscardinal.com/cardinal-sud/)99#         -> même plateforme « sysc » (unités, dates, plans, inclusions)100#     - Le Cardinal Nord + unités Cardinal Sud absentes du micro-site101#         -> portail BuildingStack edifialocation.com (« Trouvez un logement ») :102#            /Listing/Listings embarque `var units = [...]` (prix, pi², chambres,103#            GPS, contact) et les pages /b/<id> donnent dates et commodités104#   Exclus : HUMĀ phases 1-2 (connecteur dédié huma.py), Le Stellar Chicoutimi105#   (Saguenay, hors région), Solis (condos en vente), Riva Ouest (Lavaltrie,106#   en construction — aucune unité affichée nulle part).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import json111import re112113from bs4 import BeautifulSoup114115from ..schema import Listing, infer_city116from .base import BaseConnector117118EDIFIALOC = "https://edifialocation.com"119VITAL = "https://www.levitalappartements.com"120CAPELLA = "https://capellalevis.com"121CARDINAL = "https://appartementscardinal.com"122123# images à ignorer (logos, icônes, favicons, variantes responsives)124_SKIP_IMG = re.compile(r"logo|favicon|icon|Mapmarker|-\d{2,4}x\d{2,4}\.", re.I)125_IMG_RE = re.compile(126    r'https://[^"\'\s\)]+/(?:app|wp-content)/uploads/[^"\'\s\)]+'127    r'\.(?:jpe?g|webp|png)', re.I)128129130def _extract_json(html: str, marker: str):131    """Décode la structure JSON qui suit `marker` dans un script inline."""132    i = html.find(marker)133    if i < 0:134        return None135    try:136        data, _ = json.JSONDecoder().raw_decode(html[i + len(marker):])137    except Exception:138        return None139    return data140141142def _typologie(raw) -> str:143    """'4etdemiB' -> '4½', index sysc Capella (0/1/2) -> Studio/3½/4½."""144    if isinstance(raw, int):145        return {0: "Studio", 1: "3½", 2: "4½"}.get(raw, "")146    s = str(raw or "").strip().lower()147    if "studio" in s:148        return "Studio"149    m = re.search(r"(\d)\s*etdemi", s)150    if m:151        return f"{m.group(1)}½"152    m = re.search(r"(\d)\s*(?:½|1/2)", s)153    if m:154        return f"{m.group(1)}½"155    return str(raw or "").strip()156157158def _sqft(raw) -> float | None:159    try:160        v = float(str(raw).strip().replace(" ", "").replace(",", "."))161    except (TypeError, ValueError):162        return None163    return v if 80 <= v <= 20000 else None164165166class EdifiaConnector(BaseConnector):167    source_id = "edifia"168    request_delay = 0.6169    max_images = 12170171    # -- helpers ---------------------------------------------------------------172    def _page_images(self, url: str) -> list[str]:173        """Photos (uploads WordPress) d'une page de projet."""174        try:175            html = self.get(url).text176        except Exception:177            return []178        imgs = [u for u in dict.fromkeys(_IMG_RE.findall(html))179                if not _SKIP_IMG.search(u)]180        return imgs[: self.max_images]181182    # ===========================================================================183    # 1) Le Vital — sélecteur Livya (module app.livya.com embarqué)184    # ===========================================================================185    def _vital_amenities(self) -> list[str]:186        """Listes « Aires communes » et « Services et commodités » du site."""187        items: list[str] = []188        try:189            html = self.get(f"{VITAL}/espaces-communs-et-services/").text190        except Exception:191            return items192        soup = BeautifulSoup(html, "html.parser")193        # thème Bricks : chaque commodité est un bloc div.icon-box > .brxe-heading194        for el in soup.select(".icon-box .brxe-heading"):195            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))196            if 3 <= len(t) <= 90 and t not in items:197                items.append(t)198        return items[:25]199200    def _vital_units(self) -> list[dict]:201        """JSON des 230 unités : flux RSC (self.__next_f) du module Livya."""202        plans_html = self.get(f"{VITAL}/plans-et-prix/").text203        soup = BeautifulSoup(plans_html, "html.parser")204        cont = soup.select_one(".livya-module-container-plans[data-entity]")205        script = soup.select_one("script[data-client][src*='livya']")206        if cont is None or script is None:207            return []208        client = script.get("data-client")209        project = cont.get("data-project")210        entity = cont.get("data-entity")211        lang = cont.get("data-lang") or "fr"212        livya = self.get(213            f"https://app.livya.com/{lang}/{client}/projects/{project}"214            f"/plans/{entity}", params={"noLayout": "1"}).text215        chunks = re.findall(216            r'self\.__next_f\.push\(\[1,\s*"((?:[^"\\]|\\.)*)"\]\)', livya)217        blob = "".join(json.loads(f'"{c}"') for c in chunks)218        i = blob.find('"units":[')          # le tableau, pas les libellés i18n219        if i < 0:220            return []221        units = _extract_json(blob[i:], '"units":')222        return units if isinstance(units, list) else []223224    def _vital(self) -> list[Listing]:225        amenities = self._vital_amenities()226        images = self._page_images(f"{VITAL}/")227        out: list[Listing] = []228        for u in self._vital_units():229            fut = u.get("futureAvailability") or {}230            now_avail = u.get("availability") == "AVAILABLE"231            future_on = (fut.get("status") == "AVAILABLE"232                         and (fut.get("startsOn") or "")[:10])233            if not now_avail and not future_on:234                continue235            num = str(u.get("number") or "").lstrip("#").strip()236            if not num:237                continue238            if now_avail and not future_on:239                availability = "Disponible — occupation immédiate"240            else:241                availability = f"Libre le {future_on}"242            rooms = u.get("rooms") or 0243            beds = u.get("roomsBed") or 0244            unit_type = ("Studio" if beds == 0 and rooms < 1.5245                         else f"{int(rooms)}½" if float(rooms) % 1 else "")246            price = float(u.get("rentalPrice") or 0) or None247            baths = u.get("roomsBath") or 0248            balcon = u.get("balconySize") or 0249            desc = " — ".join(x for x in [250                f"Type {u['typeName']}" if u.get("typeName") else "",251                str(u.get("floorDisplayName") or ""),252                f"{u.get('unitSize')} pi²" if u.get("unitSize") else "",253                f"balcon {balcon} pi²" if balcon else "",254                f"{beds} chambre(s)" if beds else "",255                f"{baths} salle(s) de bain" if baths else "",256                str(u.get("pricePrecision") or "")] if x)257            addr = ", ".join(x for x in [258                u.get("address"), u.get("city"),259                u.get("postalCode")] if x)260            lat = u.get("latitude")261            lng = u.get("longitude")262            out.append(Listing(263                source=self.source_id,264                external_id=f"vital-{num}",265                url=f"{VITAL}/plans-et-prix/#unite-{num}",266                title=f"Le Vital — Unité {num}",267                address=addr,268                sector="Desjardins",          # Lévis (secteur Desjardins)269                city=infer_city("Desjardins"),270                unit_type=unit_type,271                price=price,272                availability=availability,273                area_sqft=_sqft(u.get("unitSize")),274                description=desc[:600],275                amenities=list(amenities),276                images=list(images),277                lat=float(lat) if lat else None,278                lng=float(lng) if lng else None,279            ))280        return out281282    # ===========================================================================283    # 2) Capella — résidence pour aînés (sélecteur « sysc », prix par unité)284    # ===========================================================================285    def _capella(self) -> list[Listing]:286        html = self.get(f"{CAPELLA}/logements-et-prix/").text287        floors = _extract_json(html, "units = ") or []288        soup = BeautifulSoup(html, "html.parser")289290        # adresse du pied de page (1500, rue Weyman, Lévis)291        address = ""292        addr_el = soup.select_one(".address div")293        if addr_el:294            address = re.sub(r"\s+", " ",295                             addr_el.get_text(", ", strip=True))296297        # inclusions (grille d'icônes sous le titre « Les inclusions »)298        amenities = ["Résidence pour aînés autonomes et semi-autonomes"]299        for h2 in soup.find_all("h2"):300            title = h2.get_text(" ", strip=True).lower()301            if "inclusion" not in title and "options" not in title:302                continue303            section = h2.find_parent("section")304            suffix = " — en option" if "options" in title else ""305            for p in (section or h2.parent).select("p.big-text"):306                t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))307                if 3 <= len(t) <= 90 and t + suffix not in amenities:308                    amenities.append(t + suffix)309        photos = [u for u in dict.fromkeys(_IMG_RE.findall(html))310                  if not _SKIP_IMG.search(u)][: self.max_images]311312        out: list[Listing] = []313        for floor in floors:314            for u in floor:315                if u.get("state") != "Available":316                    continue317                num = str(u.get("number") or "").strip()318                if not num:319                    continue320                dispo = str(u.get("available_date") or "").strip()321                indoor = u.get("indoor_area")322                balcon = u.get("balcony_area")323                desc = " — ".join(x for x in [324                    f"Type {u['type']}" if u.get("type") else "",325                    f"{indoor} pi²" if indoor else "",326                    f"balcon {balcon} pi²" if balcon else ""] if x)327                imgs = list(photos)328                plan = str(u.get("plan_img_src") or "")329                if plan.startswith("http"):330                    imgs.insert(0, plan)331                price = float(u.get("price") or 0) or None332                out.append(Listing(333                    source=self.source_id,334                    external_id=f"capella-{num}",335                    url=f"{CAPELLA}/logements-et-prix/#unite-{num}",336                    title=f"Capella (résidence pour aînés) — Unité {num}",337                    address=address,338                    sector="Desjardins",     # quartier Umano, Lévis339                    city="Lévis",340                    unit_type=_typologie(u.get("typology")),341                    price=price,342                    availability=f"Libre {dispo}" if dispo else "Disponible",343                    area_sqft=_sqft(indoor),344                    description=desc[:600],345                    amenities=list(amenities),346                    images=imgs[: self.max_images + 1],347                ))348        return out349350    # ===========================================================================351    # 3) Cardinal Sud — micro-site (sélecteur « sysc » avec dates et plans)352    # ===========================================================================353    def _cardinal_sud(self, bs_prices: dict) \354            -> tuple[list[Listing], set[str], list[str]]:355        html = self.get(f"{CARDINAL}/cardinal-sud/").text356        floors = _extract_json(html, "units = ") or []357        address, latlng = self._cardinal_map(html, "sud")358        photos = [u for u in dict.fromkeys(_IMG_RE.findall(html))359                  if not _SKIP_IMG.search(u)][: self.max_images]360361        out: list[Listing] = []362        seen: set[str] = set()363        for floor in floors:364            for u in floor:365                if u.get("state") != "Available":366                    continue367                num = str(u.get("number") or "").strip()368                if not num:369                    continue370                seen.add(num)371                dispo = str(u.get("available_date") or "").strip()372                indoor = u.get("indoor_area")373                balcon = u.get("balcony_area")374                incl = re.sub(r"\s+", " ", BeautifulSoup(375                    u.get("description") or "", "html.parser")376                    .get_text(" ", strip=True))377                desc = " — ".join(x for x in [378                    f"Type {u['type']}" if u.get("type") else "",379                    f"{indoor} pi²" if indoor else "",380                    f"balcon {balcon} pi²" if balcon else "",381                    incl] if x)382                imgs = list(photos)383                plan = str(u.get("plan_img_src") or "")384                if plan.startswith("http"):385                    imgs.insert(0, plan)386                # prix : micro-site, sinon portail BuildingStack (même unité)387                price = float(u.get("price") or 0) or None388                if price is None:389                    price = bs_prices.get(("Cardinal sud", num))390                out.append(Listing(391                    source=self.source_id,392                    external_id=f"cardinal-sud-{num}",393                    url=f"{CARDINAL}/cardinal-sud/#unite-{num}",394                    title=f"Le Cardinal Sud — Unité {num}",395                    address=address,396                    sector="Val-Bélair",397                    city="Québec",398                    unit_type=_typologie(u.get("typology")),399                    price=price,400                    availability=f"Libre {dispo}" if dispo else "Disponible",401                    area_sqft=_sqft(indoor),402                    description=desc[:600],403                    amenities=[],            # complétées via BuildingStack404                    images=imgs[: self.max_images + 1],405                    lat=latlng[0] if latlng else None,406                    lng=latlng[1] if latlng else None,407                ))408        return out, seen, photos409410    @staticmethod411    def _cardinal_map(html: str, which: str) -> tuple[str, tuple | None]:412        """Adresse + GPS depuis les marqueurs `var map_points` du micro-site."""413        points = _extract_json(html, "var map_points = ") or []414        for p in points:415            if which.lower() not in str(p.get("nom", "")).lower():416                continue417            addr = re.sub(r"\s+", " ", BeautifulSoup(418                p.get("adresse") or "", "html.parser")419                .get_text(" ", strip=True))420            try:421                lat, lng = [float(x) for x in422                            str(p["latitude_longitude"]).split(",")]423                return addr, (lat, lng)424            except (KeyError, ValueError):425                return addr, None426        return "", None427428    # ===========================================================================429    # 4) Portail BuildingStack (edifialocation.com) — Cardinal Nord + restes430    # ===========================================================================431    def _buildingstack_units(self) -> list[dict]:432        """`var units = [...]` de la page ANNONCES (toutes unités affichées)."""433        html = self.get(f"{EDIFIALOC}/Listing/Listings").text434        return _extract_json(html, "var units = ") or []435436    def _building_page(self, pub_id: str) -> tuple[dict[str, str], list[str]]:437        """Page /b/<id> : date de disponibilité par unité + commodités."""438        dates: dict[str, str] = {}439        amenities: list[str] = []440        try:441            html = self.get(f"{EDIFIALOC}/b/{pub_id}").text442        except Exception:443            return dates, amenities444        soup = BeautifulSoup(html, "html.parser")445        for a in soup.select("ul.wpb-tabs-menu a.apartment-view-potential"):446            spans = [s.get_text(" ", strip=True) for s in a.find_all("span")]447            if len(spans) >= 6 and spans[0]:448                dates[spans[0]] = spans[5]        # Unité -> Disponible449        for li in soup.select(".facilities ul li label"):450            t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))451            if 3 <= len(t) <= 90 and t not in amenities:452                amenities.append(t)453        return dates, amenities454455    def _mk_bs(self, u: dict, num: str, project: str, slug: str, url: str,456               sector: str, availability: str, amenities: list[str],457               images: list[str]) -> Listing:458        apt = u.get("Apartment") or {}459        addr = u.get("Address") or {}460        beds = apt.get("NumberOfBedrooms") or 0461        baths = apt.get("NumberOfBathrooms") or 0462        unit_type = "Studio" if beds == 0 else f"{beds + 2}½"463        desc = " — ".join(x for x in [464            f"{apt.get('Area')} pi²" if apt.get("Area") else "",465            f"{beds} chambre(s)" if beds else "",466            f"{baths} salle(s) de bain" if baths else ""] if x)467        details: dict = {}468        contacts = (u.get("Building") or {}).get("ListingEmployeesContacts") or []469        if contacts:470            c = contacts[0]471            details["contact"] = {472                k: v for k, v in [("name", c.get("FullName")),473                                  ("phone", c.get("FormattedPhoneNumber")),474                                  ("email", c.get("Email"))] if v}475        imgs = list(images)476        prev = u.get("PreviewUrl") or ""477        if prev.startswith("http"):478            imgs.insert(0, prev)479        try:480            lat, lng = float(addr.get("Latitude")), float(addr.get("Longitude"))481        except (TypeError, ValueError):482            lat = lng = None483        # prix présent dans le JSON du portail ; le site affiche484        # « Contactez-nous » (PriceFormatted) — les deux sont conservés485        price = float(apt.get("Price") or 0) or None486        return Listing(487            source=self.source_id,488            external_id=f"{slug}-{num}",489            url=url,490            title=f"{project} — Unité {num}",491            address=addr.get("Full") or "",492            sector=sector,493            city=addr.get("City") or "",494            unit_type=unit_type,495            price=price,496            price_label=str(apt.get("PriceFormatted") or ""),497            availability=availability,498            area_sqft=_sqft(apt.get("Area")),499            description=desc[:600],500            amenities=list(amenities),501            details=details,502            images=imgs[: self.max_images + 1],503            lat=lat,504            lng=lng,505        )506507    # -- fetch -----------------------------------------------------------------508    def fetch(self) -> list[Listing]:509        listings: list[Listing] = []510511        # portail BuildingStack : prix par (immeuble, unité) pour enrichir512        try:513            bs_units = self._buildingstack_units()514        except Exception:515            bs_units = []516        bs_prices: dict[tuple[str, str], float] = {}517        for u in bs_units:518            apt = u.get("Apartment") or {}519            price = float(apt.get("Price") or 0) or None520            if price:521                bs_prices[(str(u.get("BuildingName")),522                           str(apt.get("UnitName")))] = price523524        # 1) Le Vital (Livya)525        try:526            listings.extend(self._vital())527        except Exception:528            pass529530        # 2) Capella (sysc)531        try:532            listings.extend(self._capella())533        except Exception:534            pass535536        # 3) Cardinal Sud (micro-site sysc, prix complétés via le portail)537        cs_seen: set[str] = set()538        cs_photos: list[str] = []539        try:540            cs_listings, cs_seen, cs_photos = self._cardinal_sud(bs_prices)541            listings.extend(cs_listings)542        except Exception:543            cs_listings = []544545        # 4) Portail BuildingStack : Cardinal Nord (aucune unité sur le546        #    micro-site) + unités Cardinal Sud absentes du micro-site.547        #    HUMĀ (connecteur huma.py) et les immeubles hors Québec/Lévis548        #    (Le Stellar à Saguenay, etc.) sont exclus.549        bs_projects = {550            "Cardinal Nord": ("cardinal-nord", "Le Cardinal Nord",551                              f"{CARDINAL}/cardinal-nord/", "Val-Bélair"),552            "Cardinal sud": ("cardinal-sud", "Le Cardinal Sud",553                             f"{CARDINAL}/cardinal-sud/", "Val-Bélair"),554        }555        cardinal_amen: dict[str, list[str]] = {}556        by_building: dict[str, list[dict]] = {}557        for u in bs_units:558            name = str(u.get("BuildingName") or "")559            city = str((u.get("Address") or {}).get("City") or "")560            if "huma" in name.lower() or city not in ("Québec", "Lévis"):561                continue562            if name not in bs_projects:563                continue                      # immeuble inconnu : prudence564            by_building.setdefault(name, []).append(u)565566        cn_images = self._page_images(f"{CARDINAL}/cardinal-nord/") \567            if "Cardinal Nord" in by_building else []568        for name, units in by_building.items():569            slug, project, url, sector = bs_projects[name]570            pub = str((units[0].get("Building") or {})571                      .get("PublicListBuildingName") or "")572            dates, amenities = (self._building_page(pub) if pub573                                else ({}, []))574            cardinal_amen[slug] = amenities575            for u in units:576                num = str((u.get("Apartment") or {}).get("UnitName") or "")577                if not num:578                    continue579                if slug == "cardinal-sud" and num in cs_seen:580                    continue                  # déjà couvert par le micro-site581                dispo = dates.get(num, "")582                if not dispo:583                    availability = "Disponible"584                elif re.search(r"\d", dispo):     # « sept. 01, 2026 »585                    availability = f"Libre {dispo}"586                else:                             # « Disponible dès maintenant! »587                    availability = dispo588                images = cn_images if slug == "cardinal-nord" else cs_photos589                listings.append(self._mk_bs(590                    u, num, project, slug, f"{EDIFIALOC}/b/{pub}",591                    sector, availability, amenities, images))592593        # commodités du portail répercutées sur les unités micro-site Cardinal594        for lst in cs_listings:595            if not lst.amenities and cardinal_amen.get("cardinal-sud"):596                lst.amenities = list(cardinal_amen["cardinal-sud"])597598        # dédup par external_id (sécurité)599        uniq: dict[str, Listing] = {}600        for lst in listings:601            uniq.setdefault(lst.external_id, lst)602        return list(uniq.values())603
Files main
Menu

Theme