SPB Git

Repository Public

evoludev.py 11.9 KB 282 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/evoludev.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/evoludev.py : connecteur Groupe Evoludev (location.groupeevoludev.com)91#   Portail locatif maison (Laravel). La page d'accueil liste ~60 immeubles92#   (cartes : nom, adresse+ville, étiquette Disponible/Complet, prix «à partir93#   de»). Les pages projet (cache BD, seulement si l'immeuble est «Disponible»)94#   exposent un tableau d'unités (no, type, prix, statut, date, cac/sdb, pi²,95#   plan avec id d'appartement stable) + JSON-LD ApartmentComplex (description,96#   GPS, animaux, commodités).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import json102import re103104from bs4 import BeautifulSoup105106from ..schema import (Listing, normalize_unit_type, parse_area_sqft,107                      parse_price, strip_accents)108from .base import BaseConnector109110BASE = "https://location.groupeevoludev.com"111112_MODAL_ID = re.compile(r"apartmentPlanModal_(\d+)")113114115def _pets_value(raw: str) -> str | None:116    """petsAllowed du JSON-LD -> oui/non/conditions (jamais deviné)."""117    k = strip_accents((raw or "").strip().lower())118    if not k:119        return None120    if k.startswith("non") or "refus" in k or "aucun" in k:121        return "non"122    if "condition" in k or "approbation" in k:123        return "conditions"124    if k.startswith("oui") or "accepte" in k:125        return "oui"126    return None127128129class EvoludevConnector(BaseConnector):130    source_id = "evoludev"131    request_delay = 0.8132    max_pages = 1        # tout le parc est sur la page d'accueil du portail133    max_details = 45     # garde-fou pages projet (vraies requêtes)134135    def fetch(self) -> list[Listing]:136        html = self.get(BASE + "/").text137        soup = BeautifulSoup(html, "html.parser")138139        # cartes projet (dédupliquées par slug ; versions mobile/desktop en double)140        projects: dict[str, dict] = {}141        for hi in soup.select("div.headerImage[onclick]"):142            m = re.search(r"/projet/([\w-]+)", hi.get("onclick", ""))143            if not m:144                continue145            slug = m.group(1)146            if slug in projects:147                continue148            sect = hi.find_parent("section")149            tag = hi.select_one(".availabilityTag")150            title = sect.select_one(".ProjectItem__title") if sect else None151            addr = sect.select_one(".BuildingItem__address") if sect else None152            price = sect.select_one(".ProjectItem__price p") if sect else None153            addr_lines = ([l.strip() for l in addr.get_text("\n", strip=True).split("\n")]154                          if addr else [])155            projects[slug] = {156                "slug": slug,157                "name": title.get_text(strip=True) if title else slug,158                "tag": tag.get_text(" ", strip=True) if tag else "",159                "street": addr_lines[0] if addr_lines else "",160                "city": re.sub(r",?\s*QC.*$", "", addr_lines[1]).strip()161                        if len(addr_lines) > 1 else "",162                "price": re.sub(r"\s+", " ", price.get_text(" ", strip=True))163                         if price else "",164            }165166        # pages projet : uniquement les immeubles étiquetés « Disponible »167        # (Complet / livraison à venir = aucune unité offerte actuellement)168        listings: list[Listing] = []169        self._fetched = 0170        for p in projects.values():171            if not p["tag"].lower().startswith("disponible"):172                continue173            card_key = hashlib.sha1(174                f"{p['tag']}|{p['price']}|{p['name']}".encode("utf-8")).hexdigest()175            try:176                payload = self.detail(p["slug"], card_key,177                                      lambda s=p["slug"]: self._fetch_project(s))178            except Exception:179                continue180            listings.extend(self._units_to_listings(p, payload))181        return listings182183    # -- page projet ------------------------------------------------------------184    def _fetch_project(self, slug: str) -> dict:185        """Tableau des unités + JSON-LD ApartmentComplex (desc, GPS, animaux)."""186        if self._fetched >= self.max_details:187            raise RuntimeError("budget de pages projet atteint")188        self._fetched += 1189        html = self.get(f"{BASE}/projet/{slug}").text190        soup = BeautifulSoup(html, "html.parser")191        out: dict = {"units": []}192193        # JSON-LD ApartmentComplex : description, GPS, animaux, commodités194        for sc in soup.select('script[type="application/ld+json"]'):195            try:196                data = json.loads(sc.string or "")197            except Exception:198                continue199            if data.get("@type") == "ApartmentComplex":200                out["description"] = (data.get("description") or "").strip()201                out["lat"] = data.get("latitude")202                out["lng"] = data.get("longitude")203                out["pets"] = data.get("petsAllowed") or ""204                plan = data.get("accommodationFloorPlan") or {}205                out["amenities"] = plan.get("amenityFeature") or []206                imgs = data.get("image") or []207                out["building_image"] = imgs[0] if imgs else ""208                break209210        # tableau desktop des unités : no | type, prix, statut, date, cac, sdb, pi²211        seen: set[str] = set()212        for tr in soup.select(".ApartmentTable tr"):213            th = tr.find("th")214            tds = tr.find_all("td")215            if not th or len(tds) < 6:216                continue217            name = th.get_text(" ", strip=True)          # « 101 | 4 1/2 »218            if name in seen:219                continue220            seen.add(name)221            btn = tr.select_one("button[data-target]")222            m = _MODAL_ID.search(btn["data-target"]) if btn else None223            plan_img = ""224            if m:225                img = soup.select_one(f"#apartmentPlanModal_{m.group(1)} img[src]")226                plan_img = img["src"] if img else ""227            out["units"].append({228                "name": name,229                "apt_id": m.group(1) if m else "",230                "price": tds[0].get_text(" ", strip=True),231                "status": tds[1].get_text(" ", strip=True),232                "date": tds[2].get_text(" ", strip=True),233                "bedrooms": tds[3].get_text(strip=True),234                "bathrooms": tds[4].get_text(strip=True),235                "area": tds[5].get_text(" ", strip=True),236                "plan_image": plan_img,237            })238        return out239240    # -- unités -> Listings -------------------------------------------------------241    def _units_to_listings(self, p: dict, d: dict) -> list[Listing]:242        res: list[Listing] = []243        for u in d.get("units", []):244            # seules les unités affichées « Disponible » (on saute Louée/Réservée)245            if not u["status"].lower().startswith("disponible"):246                continue247            num = u["name"].split("|")[0].strip()248            ext_id = u["apt_id"] or f"{p['slug']}-{num}"249            # prix placebo de la plateforme (« 0 $ / m », « N.D. $ / m ») :250            # aucun prix publié pour cette unité — on n'affiche rien251            price_label = u["price"]252            if re.match(r"^\s*(0|N\.?D\.?)\s*\$", price_label):253                price_label = ""254            images = [i for i in (u["plan_image"], d.get("building_image", ""))255                      if i]256            details: dict = {}257            if u["bedrooms"].isdigit():258                details["bedrooms"] = int(u["bedrooms"])259            if u["bathrooms"].isdigit():260                details["bathrooms"] = int(u["bathrooms"])261            res.append(Listing(262                source=self.source_id,263                external_id=str(ext_id),264                url=f"{BASE}/projet/{p['slug']}",265                title=f"{p['name']} — Unité {num}",266                address=p["street"],267                city=p["city"],268                unit_type=normalize_unit_type(u["name"]),269                price=parse_price(price_label),270                price_label=price_label,271                availability=u["date"],272                area_sqft=parse_area_sqft(u["area"]),273                pets=_pets_value(d.get("pets", "")),274                description=d.get("description", ""),275                amenities=list(d.get("amenities", []))[:20],276                details=details,277                images=images,278                lat=d.get("lat"),279                lng=d.get("lng"),280            ))281        return res282
Files main
Menu

Theme