SPB Git

Repository Public

cogir.py 19.8 KB 463 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/cogir.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-2714#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/cogir.py : connecteur Cogir Immobilier (cogir.net)91#   Page liste « gestion-immeubles-residentiels » (rendu serveur) filtrée sur92#   les villes de la région de Québec/Lévis, du Grand Montréal (île de93#   Montréal, Laval, Longueuil/Rive-Sud, Rive-Nord proche) et de l'Outaouais94#   (Gatineau/Hull/Aylmer); chaque immeuble a95#   une fiche avec un tableau « Modèles disponibles » (type + prix à partir de)96#   et une galerie photos (DATA/PHOTO). Une annonce par modèle d'unité, sinon97#   par immeuble.98#   Exclus : Halifax/etc., résidences pour aînés/retraités/étudiantes.99#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,100#   les immeubles de la ville de Toronto (slugs toronto/scarborough/101#   north-york/east-york/etobicoke) sont aussi ingérés (province="ON",102#   budget d'immeubles séparé — le parc QC n'est jamais rogné). Les fiches103#   ON qui redirigent vers un microsite externe (608church.com, etc.) sont104#   sautées : seules celles servies par cogir.net (même gabarit français,105#   tableau « Modèles disponibles ») sont parsées. Sans la variable,106#   comportement strictement identique (QC seulement).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import os111import re112from urllib.parse import unquote, urlparse113114from bs4 import BeautifulSoup115116from ..schema import Listing, infer_city, normalize_unit_type, parse_price117from .base import BaseConnector118119# Expansion Ontario 2026-08 — gate d'environnement (défaut : QC seulement)120_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"121122123def _dedup_address(raw: str) -> str:124    """Retire les segments dupliqués des adresses Cogir125    (« 1769 Rue Careau, Québec, QC, Québec, Québec G1M 0E6 »)."""126    parts, seen = [], set()127    for seg in (s.strip() for s in (raw or "").split(",")):128        key = seg.lower()129        if not seg or key in seen:130            continue131        seen.add(key)132        parts.append(seg)133    return ", ".join(parts)134135BASE = "https://www.cogir.net"136LIST_URL = f"{BASE}/gestion-immeubles-residentiels.html"137138# Slugs d'URL correspondant à la région de Québec/Lévis139_QC_SLUGS = {140    "quebec", "sainte-foy", "ste-foy", "levis", "saint-romuald", "charny",141    "loretteville", "neufchatel", "beauport", "charlesbourg", "cap-rouge",142    "val-belair", "l-ancienne-lorette", "saint-augustin", "sillery",143    "saint-nicolas", "wendake", "vanier", "lebourgneuf",144}145_SLUG_TO_SECTOR = {146    "quebec": "", "sainte-foy": "Sainte-Foy", "ste-foy": "Sainte-Foy",147    "levis": "Lévis", "saint-romuald": "Saint-Romuald", "charny": "Charny",148    "loretteville": "Loretteville", "neufchatel": "Neufchâtel",149    "beauport": "Beauport", "charlesbourg": "Charlesbourg",150    "cap-rouge": "Cap-Rouge", "val-belair": "Val-Bélair",151    "l-ancienne-lorette": "L'Ancienne-Lorette",152    "saint-augustin": "Saint-Augustin", "sillery": "Sillery",153    "saint-nicolas": "Saint-Nicolas", "wendake": "Wendake",154    "vanier": "Vanier", "lebourgneuf": "Lebourgneuf",155}156157# Slugs d'URL du Grand Montréal et de l'Outaouais -> (secteur, ville).158# Les autres slugs (Toronto, London, Ottawa, Halifax, Sherbrooke...) restent159# exclus (hors Québec ou résidences aînés).160_GM_SLUGS = {161    # Île de Montréal162    "montreal": ("", "Montréal"),163    "vieux-montreal": ("Vieux-Montréal", "Montréal"),164    "rosemont": ("Rosemont", "Montréal"),165    "lasalle": ("LaSalle", "Montréal"),166    "pierrefonds": ("Pierrefonds", "Montréal"),167    "ville-st-laurent": ("Saint-Laurent", "Montréal"),168    "montreal-est": ("", "Montréal-Est"),169    "westmount": ("", "Westmount"),170    "pointe-claire": ("", "Pointe-Claire"),171    "dorval": ("", "Dorval"),172    # Laval173    "laval": ("", "Laval"),174    # Longueuil / Rive-Sud175    "longueuil": ("", "Longueuil"),176    "saint-hubert": ("Saint-Hubert", "Longueuil"),177    "brossard": ("", "Brossard"),178    "boucherville": ("", "Boucherville"),179    "saint-lambert": ("", "Saint-Lambert"),180    "saint-bruno": ("", "Saint-Bruno-de-Montarville"),181    "sainte-julie": ("", "Sainte-Julie"),182    "beloeil": ("", "Belœil"),183    "varennes": ("", "Varennes"),184    "saint-constant": ("", "Saint-Constant"),185    "delson": ("", "Delson"),186    "candiac": ("", "Candiac"),187    "chateauguay": ("", "Châteauguay"),188    # Rive-Nord proche189    "repentigny": ("", "Repentigny"),190    "terrebonne": ("", "Terrebonne"),191    "mascouche": ("", "Mascouche"),192    # Outaouais (expansion provinciale 2026-08)193    "gatineau": ("", "Gatineau"),194    "hull": ("Hull", "Gatineau"),195    "aylmer": ("Aylmer", "Gatineau"),196}197# Slugs de la ville de Toronto -> (secteur, ville) — expansion Ontario198# 2026-08, consommés seulement sous LOUKA_ONTARIO=1.199_ON_SLUGS = {200    "toronto": ("", "Toronto"),201    "scarborough": ("Scarborough", "Toronto"),202    "north-york": ("North York", "Toronto"),203    "east-york": ("East York", "Toronto"),204    "etobicoke": ("Etobicoke", "Toronto"),205}206# Slugs génériques : remplacés par un slug plus précis quand disponible207# (« toronto » : certains immeubles apparaissent aussi sous leur borough —208# sans effet hors gate puisqu'aucun slug ON n'est alors collecté)209_GENERIC_SLUGS = {"quebec", "montreal", "toronto"}210_BUILDING_RE = re.compile(211    r'href="(immeuble-residentiel-([a-z0-9\-]+)/(\d+)-[^"]+\.html)"')212_EXCLUDE_RE = re.compile(213    r"résidence[s]? pour (aîné|retrait)|résidence[s]? étudiante|"214    r"stationnement|commercial|rangement|entreposage", re.I)215# Variante anglaise (fiches Ontario seulement — jamais appliquée au QC)216_EXCLUDE_EN_RE = re.compile(217    r"retirement (?:residence|home|living|community)|"218    r"senior[s']*\s+(?:residence|living|housing)|"219    r"student (?:residence|housing)|parking|storage", re.I)220221222class CogirConnector(BaseConnector):223    source_id = "cogir"224    request_delay = 0.6225    max_buildings = 150      # garde-fou (région de Québec + Grand Montréal)226    max_images = 25227    # Expansion Ontario 2026-08 (gaté LOUKA_ONTARIO) : budget d'immeubles228    # séparé — le parc QC garde tout son budget max_buildings229    max_buildings_on = 40230231    def fetch(self) -> list[Listing]:232        html = self.get(LIST_URL).text233234        # 1) Immeubles des régions couvertes (dédupliqués par id numérique;235        #    on privilégie le slug le plus précis, ex. sainte-foy > quebec)236        buildings: dict[str, dict] = {}237        for m in _BUILDING_RE.finditer(html):238            path, slug, bid = m.group(1), m.group(2), m.group(3)239            if slug not in _QC_SLUGS and slug not in _GM_SLUGS \240                    and not (_ONTARIO and slug in _ON_SLUGS):241                continue242            cur = buildings.get(bid)243            if cur is None or (cur["slug"] in _GENERIC_SLUGS244                               and slug not in _GENERIC_SLUGS):245                buildings[bid] = {"path": path, "slug": slug, "id": bid}246247        # QC d'abord (ordre et plafond historiques), Ontario ensuite avec son248        # propre plafond (jamais vide hors gate : aucun slug ON collecté)249        qc_buildings = [b for b in buildings.values()250                        if b["slug"] not in _ON_SLUGS]251        on_buildings = [b for b in buildings.values()252                        if b["slug"] in _ON_SLUGS]253254        listings: list[Listing] = []255        for i, b in enumerate(qc_buildings):256            if i >= self.max_buildings:257                break258            self._ingest_building(b, "QC", listings)259        for i, b in enumerate(on_buildings):260            if i >= self.max_buildings_on:261                break262            try:263                self._ingest_building(b, "ON", listings)264            except Exception:265                continue    # l'échec ON ne doit jamais faire tomber le QC266        return listings267268    def _ingest_building(self, b: dict, province: str,269                         listings: list[Listing]) -> None:270        """Parse une fiche immeuble et ajoute ses annonces à `listings`."""271        try:272            # ON : ne pas suivre les redirections — les fiches redirigées vers273            # un microsite externe (608church.com, 107redpath.com…) sont hors274            # gabarit cogir.net et souvent 403 (éviterait d'escalader la275            # chaîne anti-bot pour rien) : on les saute.276            resp = self.get(f"{BASE}/{b['path']}",277                            allow_redirects=(province != "ON"))278            if province == "ON" and (279                    300 <= resp.status_code < 400280                    or "cogir.net" not in (urlparse(resp.url).hostname or "")):281                return282            page = resp.text283        except Exception:284            return285        soup = BeautifulSoup(page, "html.parser")286287        h1 = soup.select_one("h1")288        name = h1.get_text(strip=True) if h1 else f"Immeuble {b['id']}"289        addr_el = soup.select_one("p.adresse")290        address = ""291        if addr_el:292            address = addr_el.get_text(" ", strip=True)293            address = re.sub(r"Coordonnées complètes.*|Visite virtuelle.*",294                             "", address).strip(" »")295            address = _dedup_address(address)296        # Ontario : adresse suffixée « ON » (standard expansion 2026-08) —297        # sauf si la province y figure déjà (« ON » ou « Ontario »)298        if province == "ON" and address \299                and not re.search(r",?\s+(?:ON|Ontario)\b", address):300            address = f"{address}, ON"301302        # description (+ éventuelle section « Promotion » en tête)303        desc = ""304        d_h2 = soup.find("h2", string=re.compile("Description", re.I))305        if d_h2 and d_h2.find_parent():306            desc = d_h2.find_parent().get_text(" ", strip=True)307            desc = re.sub(r"^Description\s*", "", desc)[:600]308        p_h2 = soup.find("h2", string=re.compile(r"^\s*Promotion", re.I))309        if p_h2 and p_h2.find_parent():310            promo = p_h2.find_parent().get_text(" ", strip=True)311            promo = re.sub(r"^Promotion\s*", "", promo).strip()[:200]312            if promo:313                desc = f"Promotion : {promo}. {desc}".strip()[:700]314315        # exclusion aînés / étudiantes / commercial316        if _EXCLUDE_RE.search(name) or _EXCLUDE_RE.search(desc[:200]):317            return318        # fiches Ontario : variante anglaise (jamais appliquée au QC)319        if province == "ON" and (_EXCLUDE_EN_RE.search(name)320                                 or _EXCLUDE_EN_RE.search(desc[:200])):321            return322323        # commodités324        amenities: list[str] = []325        s_h2 = soup.find("h2", string=re.compile(326            "Services dans l'immeuble", re.I))327        if s_h2:328            ul = s_h2.find_next("ul")329            if ul:330                amenities = [li.get_text(strip=True)331                             for li in ul.select("li")][:20]332333        # photos (relatives DATA/PHOTO/... -> absolues)334        images: list[str] = []335        for im in soup.select("img[src]"):336            src = im["src"]337            if "DATA/PHOTO" not in src:338                continue339            absu = src if src.startswith("http") else f"{BASE}/{src.lstrip('/')}"340            if absu not in images:341                images.append(absu)342        images = images[: self.max_images]343344        # contact de l'immeuble (liens tel:/mailto:, hors pied de page345        # corporatif info@cogir.net / 1-866-671-6381)346        contact: dict = {}347        for a in soup.select('a[href^="tel:"]'):348            digits = re.sub(r"\D", "", a.get("href", ""))[-10:]349            if len(digits) == 10 and not digits.startswith("866"):350                contact["phone"] = (f"{digits[:3]}-{digits[3:6]}-"351                                    f"{digits[6:]}")352                break353        for a in soup.select('a[href^="mailto:"]'):354            email = unquote(a["href"].removeprefix("mailto:")).strip()355            if email and email.lower() != "info@cogir.net":356                contact["email"] = email357                break358        details_extra = {"contact": contact} if contact else {}359360        if province == "ON":361            # ville de Toronto : slug -> (secteur/borough, ville)362            sector, city = _ON_SLUGS[b["slug"]]363        elif b["slug"] in _GM_SLUGS:364            sector, city = _GM_SLUGS[b["slug"]]365        else:366            sector = _SLUG_TO_SECTOR.get(b["slug"], "")367            if not sector:368                # essaie de déduire le secteur du nom (« Loretteville »)369                for s in _SLUG_TO_SECTOR.values():370                    if s and s.lower() in name.lower():371                        sector = s372                        break373            city = infer_city(sector or b["slug"], default="Québec")374        url = f"{BASE}/{b['path']}"375376        # 2) Une annonce par modèle du tableau « Modèles disponibles »377        #    (#tableModele : colType / colModele / colPrix). Les modèles378        #    marqués « Pas disponible » ou « Liste d'attente » sont exclus.379        rows = []380        table = soup.select_one("table#tableModele") or soup.find("table")381        for tr in table.select("tbody tr") if table else []:382            typ_el = tr.select_one("td.colType")383            mod_el = tr.select_one("td.colModele")384            prix_el = tr.select_one("td.colPrix")385            tds = tr.select("td")386            typ = (typ_el.get_text(" ", strip=True) if typ_el387                   else (tds[0].get_text(" ", strip=True) if tds else ""))388            modele = mod_el.get_text(" ", strip=True) if mod_el else ""389            # certains immeubles mettent « À partir de » dans colModele390            if re.fullmatch(r"à partir de\s*", modele, re.I):391                modele = ""392            if prix_el is not None:393                price_txt = prix_el.get_text(" ", strip=True)394            else:395                price_txt = next((td.get_text(" ", strip=True)396                                  for td in tds[1:]397                                  if "$" in td.get_text()), "")398            if not typ or not re.match(399                    r"^\d\s*1/2|^\d\s*½|^Studio|^Loft|^Penthouse",400                    typ, re.I):401                continue402            if re.search(r"pas disponible|liste d'attente", price_txt,403                         re.I):404                continue          # modèle affiché mais non offert405            price_txt = re.sub(r"à partir de", "", price_txt, flags=re.I)406            rows.append((typ, modele, price_txt.strip()))407408        if rows:409            seen_ext: set[str] = set()410            for typ, modele, price_txt in rows:411                ut = normalize_unit_type(typ)412                ext = f"{b['id']}-{re.sub(r'[^a-z0-9]+', '', ut.lower()) or 'u'}"413                if ext in seen_ext:414                    # 2e modèle du même type (ex. « 3 1/2 + den ») :415                    # suffixe du nom de modèle pour un uid unique416                    suffix = re.sub(r"[^a-z0-9]+", "-",417                                    modele.lower()).strip("-")418                    ext = f"{ext}-{suffix or len(seen_ext)}"419                    if ext in seen_ext:420                        continue421                seen_ext.add(ext)422                label = (f"{ut} ({modele})"423                         if modele and modele.lower() != typ.lower()424                         else ut)425                listings.append(Listing(426                    source=self.source_id,427                    external_id=ext,428                    url=url,429                    title=f"{name} — {label}",430                    address=address,431                    sector=sector,432                    city=city,433                    province=province,434                    unit_type=ut,435                    price=parse_price(price_txt),436                    price_label=(f"À partir de {price_txt}"437                                 if price_txt else ""),438                    availability="Disponible" if price_txt else "",439                    description=desc,440                    amenities=amenities,441                    details=dict(details_extra),442                    images=images,443                ))444        else:445            listings.append(Listing(446                source=self.source_id,447                external_id=b["id"],448                url=url,449                title=name,450                address=address,451                sector=sector,452                city=city,453                province=province,454                unit_type="",455                price=None,456                price_label="",457                availability="",458                description=desc,459                amenities=amenities,460                details=dict(details_extra),461                images=images,462            ))463
Files main
Menu

Theme