SPB Git

Repository Public

logisco.py 17.4 KB 416 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/logisco.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/logisco.py : connecteur Logisco (logisco.com)91#   Site rendu serveur. Crawl : page liste principale (+ pages villes) pour92#   découvrir les pages projets, puis extraction des unités disponibles93#   (cartes .unitCard) sur chaque page projet. Une annonce par unité.94#   Chaque page unité (mise en cache via self.detail, plafond 150 vraies95#   requêtes/sync) apporte : JSON-LD (adresse avec no d'unité + code postal,96#   étage, téléphone, plan de l'unité), superficie/étage/dispo structurés97#   (sommaire .unitHeader) et les 4 sections de commodités (Inclusions,98#   Particularités, Services offerts, Espaces communs).99#   Villes retenues : Québec, Lévis, Saint-Augustin-de-Desmaures100#   (Donnacona et autres villes hors région exclues).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import html as htmllib106import json107import re108from urllib.parse import urljoin109110from bs4 import BeautifulSoup111112from ..schema import Listing, infer_city, normalize_unit_type, parse_price113from .base import BaseConnector114115BASE = "https://logisco.com"116LIST_URL = f"{BASE}/fr/appartements-a-louer"117118# villes de la région Québec/Lévis retenues (segment d'URL -> nom de ville)119CITY_MAP = {120    "quebec": "Québec",121    "levis": "Lévis",122    "saint-augustin-de-desmaures": "Saint-Augustin-de-Desmaures",123}124125PROJECT_HREF_RE = re.compile(126    r'href="(https://logisco\.com/fr/appartements-a-louer/([a-z0-9\-]+(?:/[a-z0-9\-]+)*))"'127)128STATIC_IMG_RE = re.compile(129    r'(?:src|data-src|href)="(https://logisco\.com/static/[^"]+\.(?:webp|jpe?g|png))"'130)131EXCLUDE_UNIT_RE = re.compile(r"stationnement|parking|rangement|commercial|garage", re.I)132133134def _text(el, sep: str = " ") -> str:135    """Texte d'un élément, robuste aux <template> Vue du site.136137    bs4 classe les chaînes situées sous une balise <template> comme138    TemplateString et les exclut de get_text() par défaut ; or les cartes139    d'unités de Logisco se retrouvent imbriquées sous de telles balises.140    `types=None` force la prise en compte de toutes les chaînes.141    """142    if el is None:143        return ""144    return el.get_text(sep, strip=True, types=None)145146147class _DetailBudget(Exception):148    """Plafond de vraies requêtes de pages unité atteint pour cette synchro."""149150151class LogiscoConnector(BaseConnector):152    source_id = "logisco"153    request_delay = 0.6154    max_projects = 40         # garde-fou : nb max de pages projets crawlées155    max_project_imgs = 15     # nb max de photos projet par annonce156    max_details = 150         # plafond de VRAIES requêtes de pages unité/sync157158    def __init__(self) -> None:159        super().__init__()160        self._detail_fetches = 0161162    # -- découverte des pages projets ----------------------------------------163    def _discover_projects(self) -> dict[str, tuple[str, str]]:164        """Retourne {url_projet: (segment_ville, segment_secteur)}."""165        pages = []166        try:167            pages.append(self.get(LIST_URL).text)168        except Exception:169            pass170        for city in CITY_MAP:171            try:172                pages.append(self.get(f"{LIST_URL}/{city}").text)173            except Exception:174                continue175176        projects: dict[str, tuple[str, str]] = {}177        for html in pages:178            for url, path in PROJECT_HREF_RE.findall(html):179                parts = path.split("/")180                city = parts[0]181                if city not in CITY_MAP:182                    continue  # ex. Donnacona et autres villes hors région183                # quebec/levis : ville/secteur/projet (3 segments)184                # saint-augustin : ville/projet (2 segments)185                if city in ("quebec", "levis"):186                    if len(parts) != 3:187                        continue188                    sector = parts[1]189                elif len(parts) == 2:190                    sector = city191                else:192                    continue193                projects.setdefault(url, (city, sector))194        return projects195196    # -- extraction d'une page projet -----------------------------------------197    def _project_images(self, html: str) -> list[str]:198        """Photos du projet (sans logos ni plans d'unités), dédupliquées."""199        imgs = []200        for u in STATIC_IMG_RE.findall(html):201            name = u.rsplit("/", 1)[-1].lower()202            if name.startswith(("logo-", "plan-")) or "logo" in name.split("-")[:1]:203                continue204            imgs.append(u)205        return list(dict.fromkeys(imgs))[: self.max_project_imgs]206207    def fetch(self) -> list[Listing]:208        projects = self._discover_projects()209        listings: dict[str, Listing] = {}210211        for i, (proj_url, (city_seg, sector_seg)) in enumerate(projects.items()):212            if i >= self.max_projects:213                break214            try:215                html = self.get(proj_url).text216            except Exception:217                continue218            soup = BeautifulSoup(html, "html.parser")219220            project_name = ""221            h1 = soup.find("h1")222            if h1:223                # retirer le slogan SEO : « District GC • Appartements … »,224                # « L'AMALGAM - Grands appartements à louer … »225                project_name = re.split(r"\s+[•|–—]\s+|\s+-\s+", _text(h1))[0].strip()226            proj_imgs = self._project_images(html)227            cards = soup.select("li.unitCard, .unitCard")228            n_dispo = len(cards)229230            for card in cards:231                try:232                    unit_gtm_type = (card.get("data-gtm-unit-type") or "").upper()233                    if unit_gtm_type and unit_gtm_type != "APARTMENT":234                        continue235                    link = card.select_one("a.unitCard-link")236                    if not link or not link.get("href"):237                        continue238                    url = urljoin(BASE, link["href"])239240                    ext_id = card.get("data-gtm-unit-id") or ""241                    if not ext_id:242                        ext_id = url.rstrip("/").rsplit("/", 1)[-1]243244                    title = _text(card.select_one(".unitCard-title"))245                    if EXCLUDE_UNIT_RE.search(title):246                        continue247248                    address = _text(card.select_one(".unitCard-address"))249250                    # secteur : « Desjardins, Lévis » -> « Desjardins »251                    sector = ""252                    map_el = card.select_one(".unitCard-address--map")253                    if map_el:254                        sector = _text(map_el).split(",")[0].strip()255                    if not sector:256                        sector = sector_seg.replace("-", " ").title()257258                    sizes = [_text(s) for s in card.select(".unitCard-size")]259                    unit_type = ""260                    for s in sizes:261                        if re.match(r"^\d\s*(?:1/2|½)|^(studio|loft)", s, re.I):262                            unit_type = s263                            break264265                    price_label = _text(card.select_one(".unitCard-price"))266267                    availability = _text(card.select_one(".unitCard-dispo"))268269                    amenities = list(dict.fromkeys(270                        t for t in (_text(sr) for sr in271                                    card.select(".unitCard-services .sr-only"))272                        if t273                    ))274275                    images = []276                    img_el = card.select_one("img.unitCard-image")277                    if img_el and img_el.get("src"):278                        images.append(urljoin(BASE, img_el["src"]))279                    images += [u for u in proj_imgs if u not in images]280281                    extra = ", ".join(s for s in sizes if s != unit_type)282                    desc_bits = []283                    if project_name:284                        desc_bits.append(f"Projet {project_name}")285                    if extra:286                        desc_bits.append(extra)287                    desc_bits.append(f"{n_dispo} unité(s) disponible(s) dans le projet")288289                    default_city = CITY_MAP.get(city_seg, "Québec")290                    full_title = (f"{project_name} — {title}"291                                  if project_name and title else title or project_name)292293                    lst = Listing(294                        source=self.source_id,295                        external_id=str(ext_id),296                        url=url,297                        title=full_title or f"Unité {ext_id}",298                        address=address,299                        sector=sector,300                        city=infer_city(sector, default=default_city),301                        unit_type=normalize_unit_type(unit_type),302                        price=parse_price(price_label),303                        price_label=price_label,304                        availability=availability,305                        description=" — ".join(desc_bits)[:600],306                        amenities=amenities,307                        images=images,308                    )309310                    # page unité (avec cache BD) : adresse complète, superficie,311                    # étage, téléphone, plan, sections de commodités312                    # préfixe v2 = version de l'extraction (invalide le cache)313                    key = "v2:" + hashlib.sha1(" | ".join(314                        [title, address, price_label, availability]315                        + sizes + amenities).encode("utf-8")).hexdigest()316                    try:317                        payload = self.detail(318                            str(ext_id), key, lambda u=url: self._fetch_unit(u))319                    except _DetailBudget:320                        payload = {}      # plafond atteint : complété au prochain sync321                    except Exception:322                        payload = {}323                    self._apply_unit(lst, payload)324325                    listings[ext_id] = lst326                except Exception:327                    continue  # ne jamais planter sur une carte malformée328329        return list(listings.values())330331    # -- page unité ------------------------------------------------------------332    def _fetch_unit(self, url: str) -> dict:333        if self._detail_fetches >= self.max_details:334            raise _DetailBudget(url)335        self._detail_fetches += 1336        soup = BeautifulSoup(self.get(url).text, "html.parser")337        out: dict = {}338339        # JSON-LD « apartment » : adresse (no d'unité + code postal), étage,340        # téléphone du bureau de location, plan de l'unité341        for sc in soup.find_all("script", type="application/ld+json"):342            try:343                data = json.loads(sc.string or "")344            except Exception:345                continue346            if not (isinstance(data, dict)347                    and str(data.get("@type", "")).lower() == "apartment"):348                continue349            addr = data.get("address") or {}350            # certaines valeurs JSON-LD contiennent des entités HTML (&#039;)351            street = htmllib.unescape((addr.get("streetAddress") or "")).strip()352            if street:353                bits = [street,354                        htmllib.unescape((addr.get("addressLocality") or "")).strip(),355                        (addr.get("postalCode") or "").strip()]356                out["address"] = ", ".join(b for b in bits if b)357            tel = re.sub(r"\D", "", str(data.get("telephone") or ""))358            tel = tel[1:] if len(tel) == 11 and tel.startswith("1") else tel359            if len(tel) == 10:360                out["phone"] = f"{tel[:3]}-{tel[3:6]}-{tel[6:]}"361            fl = str(data.get("floorLevel") or "").strip()362            if fl.isdigit():363                out["floor"] = int(fl)364            img = data.get("image") or ""365            if isinstance(img, str) and img.startswith("http"):366                out["plan"] = img367            break368369        # sommaire de l'unité : superficie, étage, disponibilité (structurés)370        for info in soup.select(".unitHeader-info"):371            label = _text(info.select_one(".unitHeader-infoLabel")).lower()372            value = _text(info.select_one(".unitHeader-infoValue"))373            if "superficie" in label:374                m = re.search(r"([\d\s ]+)\s*pi", value)375                if m:376                    try:377                        v = float(re.sub(r"[\s ]", "", m.group(1)))378                        if 80 <= v <= 20000:379                            out["area_sqft"] = v380                    except ValueError:381                        pass382            elif "tage" in label and re.fullmatch(r"\d{1,2}", value):383                out["floor"] = int(value)384            elif "disponibilit" in label and value:385                out["availability"] = value386387        # sections : Inclusions / Particularités / Services offerts /388        # Espaces communs (items texte, fidèles — « Rangement supplémentaire ($) »)389        amen: list[str] = []390        for item in soup.select(".projectServices-listItem"):391            t = _text(item)392            if t:393                amen.append(t)394        out["amenities"] = list(dict.fromkeys(amen))[:40]395        return out396397    def _apply_unit(self, lst: Listing, payload: dict) -> None:398        if not payload:399            return400        if payload.get("address"):401            lst.address = payload["address"]402        if payload.get("area_sqft"):403            lst.area_sqft = payload["area_sqft"]404        if payload.get("availability") and not lst.availability:405            lst.availability = payload["availability"]406        if payload.get("floor") is not None:407            lst.details["floor"] = payload["floor"]408        if payload.get("phone"):409            lst.details.setdefault("contact", {})["phone"] = payload["phone"]410        for a in payload.get("amenities", []):411            if a not in lst.amenities:412                lst.amenities.append(a)413        plan = payload.get("plan")414        if plan and plan not in lst.images:415            lst.images.append(plan)416
Files main
Menu

Theme