SPB Git

Repository Public

morin.py 13.7 KB 329 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/morin.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-10-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/morin.py : connecteur Constructions Morin (constructionsmorin.com)91#   Constructeur-locateur : apparts neufs tout inclus à Sherbrooke92#   (St-Élie/Rock-Forest, Fleurimont), Ascot Corner, East Angus, Windsor et93#   Lac-Mégantic. WordPress + Avada : la page /appartements-a-louer/ est94#   rendue serveur — un bloc .appartement_list_block par TYPE d'unité95#   disponible dans un immeuble (adresse h3, ville/secteur, projet, badge de96#   type « 4 ½ », « N disponibles », « À partir de … $ », date « Disponible97#   dès le … », chambres/sdb/stationnement). Granularité = type d'unité par98#   immeuble (les unités individuelles de la fiche n'ont ni prix ni dispo99#   propres). Les fiches (via self.detail, cache BD) ajoutent la description100#   (inclusions) et la galerie. external_id = slug projet/unité (stable).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106import time107108import requests109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, parse_price112from .base import BaseConnector113114BASE = "https://constructionsmorin.com"115LIST_URL = f"{BASE}/appartements-a-louer/"116117_VARIANT_IMG = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)118_KNOWN_CITIES = ["Sherbrooke", "Ascot Corner", "East Angus", "Windsor",119                 "Lac-Mégantic"]120121122class MorinConnector(BaseConnector):123    source_id = "morin"124    request_delay = 0.6125    max_details = 25      # garde-fou fiches détail (vraies requêtes)126127    def fetch(self) -> list[Listing]:128        html = self._get_list_with_retry().text129        soup = BeautifulSoup(html, "html.parser")130131        listings: dict[str, Listing] = {}132        for block in soup.select(".appartement_list_block"):133            try:134                lst = self._parse_block(block)135            except Exception:136                continue137            if lst and lst.external_id not in listings:138                listings[lst.external_id] = lst139140        # fiches (cache BD) : description (inclusions) + galerie du projet141        self._fetched = 0142        for lst in listings.values():143            key = hashlib.sha1(144                f"{lst.title}|{lst.price_label}|{lst.availability}"145                .encode("utf-8")).hexdigest()146            try:147                payload = self.detail(lst.external_id, key,148                                      lambda u=lst.url: self._fetch_detail(u))149            except Exception:150                continue151            if payload.get("description"):152                lst.description = payload["description"]153            if payload.get("images"):154                lst.images = list(dict.fromkeys(payload["images"] + lst.images))[:20]155            if payload.get("area_label") and lst.area_sqft is None:156                # « Superficie: 860-1140 pi² » -> borne basse (plage réelle157                # conservée en commodité)158                m = re.match(r"([\d\s]+)", payload["area_label"])159                if m:160                    try:161                        val = float(m.group(1).replace(" ", ""))162                        if 80 <= val <= 20000:163                            lst.area_sqft = val164                    except ValueError:165                        pass166                lst.amenities = list(dict.fromkeys(167                    lst.amenities + [f"Superficie : {payload['area_label']}"]))168        return list(listings.values())169170    # L'hébergeur (MySQL) flappe par épisodes : 500 vides intermittents entre171    # deux 200 parfaits. Un hoquet 5xx isolé ne doit pas tuer le sync — 3172    # tentatives avec backoff ; erreur franche inchangée si les 3 échouent.173    def _get_list_with_retry(self):174        last: Exception | None = None175        for attempt in range(3):176            if attempt:177                time.sleep(5 * attempt)178            try:179                return self.get(LIST_URL)180            except requests.HTTPError as exc:181                r = getattr(exc, "response", None)182                if r is None or getattr(r, "status_code", 0) < 500:183                    raise184                last = exc185        raise last  # type: ignore[misc]186187    # -- un bloc = un type d'unité disponible dans un immeuble ------------------------188    def _parse_block(self, block) -> Listing | None:189        link = block.select_one("a[href*='/appartements-a-louer/']")190        if not link:191            return None192        url = link["href"]193        m = re.search(r"/appartements-a-louer/([^?#]+?)/?$", url)194        if not m:195            return None196        slug = m.group(1).strip("/")           # « horizon/5565-…-4-1-2 »197198        h3 = block.select_one("h3")199        address = re.sub(r"\s+", " ", h3.get_text(" ", strip=True)).strip() if h3 else ""200201        # ville + secteur : « Ascot Corner », « Sherbrooke Secteur St-Élie/… »202        sec_el = block.select_one(".appartement_list_information_secteur")203        sec_txt = re.sub(r"\s+", " ",204                         sec_el.get_text(" ", strip=True)).strip() if sec_el else ""205        city, sector = "", ""206        for c in _KNOWN_CITIES:207            if sec_txt.lower().startswith(c.lower()):208                city = c209                sector = re.sub(r"^Secteur\s+", "", sec_txt[len(c):].strip())210                break211        if not city:212            city = sec_txt213214        project_el = sec_el.find_next_sibling("div") if sec_el else None215        project = re.sub(r"\s+", " ", project_el.get_text(" ", strip=True)).strip() \216            if project_el else ""217218        # type d'unité : badge « 4 ½ »219        badge = block.select_one(".appartement_list_badge_libre")220        unit_type = normalize_unit_type(221            badge.get_text(" ", strip=True) if badge else "")222        if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",223                            unit_type or ""):224            unit_type = ""225226        # « Disponible dès le 1er février 2027! » (bandeau de la carte)227        tag = block.select_one(".appartement_list_tag")228        availability = re.sub(r"\s+", " ",229                              tag.get_text(" ", strip=True)).strip() if tag else ""230231        # « À partir de | 1395$ »232        prix_el = block.select_one(".appartement_list_information_prix_montant")233        price_label = ""234        price = None235        if prix_el:236            amount = prix_el.get_text(" ", strip=True)237            price_label = f"À partir de {amount}"238            price = parse_price(re.sub(r"(\d)\s(\d{3})", r"\1\2", amount))239240        # commodités structurées de la carte : dispo/nb unités, chambres, sdb,241        # stationnement, superficie242        amenities: list[str] = []243        libre = block.select_one(".appartement_list_libre_txt")244        if libre:245            amenities.append(re.sub(r"\s+", " ",246                                    libre.get_text(" ", strip=True)).strip())247        nb = block.select_one(".appartement_list_nb_appartement")248        if nb:249            amenities.append(re.sub(r"\s+", " ",250                                    nb.get_text(" ", strip=True)).strip())251        for unit in block.select(".appartement_list_info_block > div"):252            val = unit.select_one(".appartement_list_info_block_unit span")253            lab = unit.select_one(".appartement_list_info_block_unit_title")254            if val and lab:255                amenities.append(f"{val.get_text(strip=True)} "256                                 f"{lab.get_text(strip=True)}")257        area = None258        m2 = re.search(r"Superficie\s*:\s*([\d\s]+)(?:-|–|à)?([\d\s]*)pi",259                       block.get_text(" ", strip=True))260        if m2:261            try:262                area = float(m2.group(1).replace(" ", ""))263            except ValueError:264                pass265266        # visuel de la carte (background-image du bloc)267        images: list[str] = []268        bg = block.select_one(".appartement_list_image_bg")269        if bg:270            mi = re.search(r"url\('([^']+)'\)", bg.get("style") or "")271            if mi and mi.group(1).startswith("http"):272                images.append(_VARIANT_IMG.sub("", mi.group(1)))273274        title = f"{unit_type} — {address}" if unit_type else address275        if project:276            title += f" ({project})"277278        return Listing(279            source=self.source_id,280            external_id=slug,281            url=url,282            title=title,283            address=address,284            sector=sector,285            city=city,286            unit_type=unit_type,287            price=price,288            price_label=price_label,289            availability=availability,290            area_sqft=area,291            amenities=amenities,292            details={"project": project} if project else {},293            images=images,294        )295296    # -- fiche type d'unité -------------------------------------------------------297    def _fetch_detail(self, url: str) -> dict:298        if self._fetched >= self.max_details:299            raise RuntimeError("budget de fiches détail atteint")300        self._fetched += 1301        html = self.get(url).text302        soup = BeautifulSoup(html, "html.parser")303        out: dict = {}304305        # « Votre appartement luxueux comprend : » + liste d'inclusions306        head = soup.find(string=re.compile(r"appartement.*comprend", re.I))307        if head:308            ul = head.parent.find_next("ul")309            if ul:310                items = [re.sub(r"\s+", " ", li.get_text(" ", strip=True)).strip(" ;")311                         for li in ul.select("li")]312                out["description"] = "Votre appartement comprend : " + \313                                     " ; ".join(t for t in items if t)[:1400]314315        # « Superficie: 860-1140 pi² » (fiche du type d'unité)316        ma = re.search(r"Superficie\s*:\s*([\d\s]+(?:[-–à]\s*[\d\s]+)?)\s*pi",317                       soup.get_text(" ", strip=True))318        if ma:319            out["area_label"] = re.sub(r"\s+", " ", ma.group(1)).strip() + " pi²"320321        images: list[str] = []322        for img in soup.select("img[src*='/wp-content/uploads/']"):323            src = _VARIANT_IMG.sub("", str(img.get("src") or ""))324            if src.startswith("http") and src not in images \325                    and not re.search(r"logo|icon|favicon|Projet-", src):326                images.append(src)327        out["images"] = images[:15]328        return out329
Files main
Menu

Theme