SPB Git

Repository Public

ferrovia.py 12.9 KB 305 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/ferrovia.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-1814#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/ferrovia.py : connecteur Ferrovia (ferroviamirabel.com)91#   Projet de condos locatifs neufs à Mirabel (secteur Saint-Janvier), 4 phases.92#   WordPress + wpDataTables rendues côté serveur : chaque page « Disponibilités »93#   contient un <table.wpDataTable> (UNITÉ, MODÈLE, ÉTAGE, PIÈCES, SUPERFICIE,94#   SALLE D'EAU SUPP., DISPONIBILITÉ, PRIX, STATUT, PLAN). On ne retient que les95#   lignes STATUT = « Disponible » ; external_id = phase + numéro d'unité.96#   Le site précise que les logements sont non-fumeurs et sans animaux.97#   Prix : colonne présente mais vide à ce jour — jamais inventé.98#   Galeries (3 requêtes/sync) : /interieurs-phase3/ et /interieurs-phase4/99#   publient une image par MODÈLE (A, A', B'… — « A' » = fichiers « A1 ») et100#   /photos-unites/ une galerie générale du projet -> image du modèle en tête101#   puis photos générales. Adresse civique publiée sur /contact-information/ :102#   14340, rue Roger-Thomas (repli codé en dur si la page change).103# -----------------------------------------------------------------------------104from __future__ import annotations105106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price111from .base import BaseConnector112113BASE = "https://www.ferroviamirabel.com"114PHASES = [115    ("1", f"{BASE}/disponibilites-prix-plans-phase1/"),116    ("3", f"{BASE}/disponibilites-phase-3/"),117    ("4", f"{BASE}/disponibilites-phase-4/"),118]119CONTACT_URL = f"{BASE}/contact-information/"120GALLERY_PAGES = {"3": f"{BASE}/interieurs-phase3/",121                 "4": f"{BASE}/interieurs-phase4/"}122PHOTOS_URL = f"{BASE}/photos-unites/"123124_FALLBACK_ADDR = "14340 rue Roger-Thomas"125_IMG_EXT_RE = re.compile(r"\.(?:jpg|jpeg|png|webp)$", re.I)126_SKIP_IMG_RE = re.compile(r"logo|icon|favicon|couleur_fond|slider-|accueil|"127                          r"phases\.jpg|-\d{2,4}x\d{2,4}\.", re.I)128129130def _model_key(url: str) -> str | None:131    """Nom de fichier -> lettre de modèle (« Ferrovia_Phase4_A1M.png » -> A1,132    « ph3-H-new.png » -> H, « Modele-F-web2.jpg » -> F) ; None si générique."""133    b = url.rsplit("/", 1)[-1]134    b = re.sub(r"\.(?:jpg|jpeg|png|webp)$", "", b, flags=re.I)135    b = re.sub(r"(?i)^ferrovia_phase-?\d_?", "", b)136    b = re.sub(r"(?i)^(phase\d|ph\d|modele)-", "", b)137    b = re.sub(r"(?i)-(ph\d|new\d*|web\d*)", "", b)138    m = re.fullmatch(r"(?i)([a-i]1?)m?", b.strip("-_ "))139    return m.group(1).upper() if m else None140141142class FerroviaConnector(BaseConnector):143    source_id = "ferrovia"144    request_delay = 0.7145    max_general_photos = 6      # photos générales ajoutées à chaque annonce146147    # -- adresse civique du projet (page contact, repli constant) --------------148    def _project_address(self) -> str:149        try:150            text = BeautifulSoup(self.get(CONTACT_URL).text,151                                 "html.parser").get_text("\n", strip=True)152        except Exception:153            return _FALLBACK_ADDR154        m = re.search(r"(\d{3,5}),?\s+(rue\s+Roger-Thomas)", text, re.I)155        return f"{m.group(1)} {m.group(2)}" if m else _FALLBACK_ADDR156157    # -- galeries : {phase: {modèle: image}} + photos générales -----------------158    def _galleries(self) -> tuple[dict[str, dict[str, str]], list[str]]:159        by_model: dict[str, dict[str, str]] = {}160        for phase, url in GALLERY_PAGES.items():161            try:162                html = self.get(url).text163            except Exception:164                continue165            for u in re.findall(r'(?:src|href)="(https?://[^"]+)"', html):166                if not _IMG_EXT_RE.search(u) or _SKIP_IMG_RE.search(u):167                    continue168                key = _model_key(u)169                if key:170                    by_model.setdefault(phase, {}).setdefault(key, u)171        general: list[str] = []172        try:173            html = self.get(PHOTOS_URL).text174            for u in re.findall(r'href="(https?://[^"]+)"', html):175                if _IMG_EXT_RE.search(u) and not _SKIP_IMG_RE.search(u) \176                        and "/uploads/" in u and u not in general:177                    general.append(u)178        except Exception:179            pass180        return by_model, general[: self.max_general_photos]181182    def fetch(self) -> list[Listing]:183        self._address = self._project_address()184        self._model_imgs, self._general_imgs = self._galleries()185        listings: dict[str, Listing] = {}186        for phase, url in PHASES:187            try:188                html = self.get(url).text189            except Exception:190                continue191            self._parse_phase(phase, url, html, listings)192        return list(listings.values())193194    def _parse_phase(self, phase: str, url: str, html: str,195                     listings: dict[str, Listing]) -> None:196        soup = BeautifulSoup(html, "html.parser")197        table = soup.select_one("table.wpDataTable")198        if table is None:199            return200        heads = [th.get_text(" ", strip=True).lower()201                 for th in table.select("thead th")]202203        def col(row_cells, *keys):204            for key in keys:205                for i, h in enumerate(heads):206                    if key in h and i < len(row_cells):207                        return row_cells[i]208            return None209210        for tr in table.select("tbody tr"):211            cells = tr.find_all("td")212            texts = [re.sub(r"\s+", " ", td.get_text(" ", strip=True))213                     for td in cells]214            statut = col(texts, "statut") or ""215            if not re.match(r"(?i)disponible", statut):216                continue                          # loué / réservé : on saute217            unit = col(texts, "unité", "unite") or ""218            if not unit:219                continue220            pieces = col(texts, "pièces", "pieces") or ""221            unit_type = normalize_unit_type(pieces)222            if not re.fullmatch(r"\d½|Studio|Loft", unit_type or ""):223                continue                          # ligne non résidentielle224            modele = col(texts, "modèle", "modele") or ""225            etage = col(texts, "étage", "etage") or ""226            superficie = col(texts, "superficie") or ""227            demi_sdb = col(texts, "salle d'eau", "salle d’eau") or ""228            dispo = col(texts, "disponibilité", "disponibilite") or ""229            prix = col(texts, "prix") or ""       # vide à ce jour sur le site230231            area = None232            m = re.match(r"([\d\s,.]+)$", superficie)233            if m:234                try:235                    area = float(m.group(1).replace(" ", "").replace(",", ""))236                except ValueError:237                    area = None238239            plan_td = col(cells, "plan")240            plan_url = ""241            if plan_td is not None:242                a = plan_td.find("a", href=True)243                if a:244                    plan_url = a["href"]245246            details = {"phase": phase, "smoking": False}247            if modele:248                details["model"] = modele249            if etage:250                details["floor"] = etage251            if plan_url:252                details["plan_pdf"] = plan_url253            amenities = []254            if re.match(r"(?i)oui", demi_sdb):255                amenities.append("Salle d'eau supplémentaire")256257            # galerie : image du modèle (si publiée) puis photos générales258            images: list[str] = []259            mk = re.sub(r"[’']", "1", modele).replace(" ", "").upper()260            model_img = (self._model_imgs.get(phase) or {}).get(mk)261            if model_img:262                images.append(model_img)263            images.extend(u for u in self._general_imgs if u not in images)264265            desc_bits = [f"Unité {unit} ({pieces}) du projet Ferrovia, "266                         f"condos locatifs neufs à Mirabel dans le secteur "267                         f"de Saint-Janvier (phase {phase})."]268            facts = []269            if modele:270                facts.append(f"modèle {modele}")271            if etage:272                facts.append(f"étage {etage}")273            if area:274                facts.append(f"{area:g} pi²")275            if re.match(r"(?i)oui", demi_sdb):276                facts.append("salle d'eau supplémentaire")277            if facts:278                desc_bits.append(", ".join(facts).capitalize() + ".")279            if dispo:280                desc_bits.append(f"Disponibilité : {dispo}.")281            desc_bits.append("Les logements sont non-fumeurs et les animaux "282                             "ne sont pas admis. Aucun loyer affiché sur le "283                             "site : contactez le locateur pour les prix.")284285            ext = f"phase{phase}-{unit}"286            listings[ext] = Listing(287                source=self.source_id,288                external_id=ext,289                url=url,290                title=f"Ferrovia phase {phase} — unité {unit} ({pieces})",291                address=self._address,292                sector="Saint-Janvier",293                city="Mirabel",294                unit_type=unit_type,295                price=parse_price(prix),296                price_label=prix,297                availability=dispo,               # « Automne 2026 », « ÉTÉ 2026 »298                area_sqft=area,299                pets="non",                       # note du site : animaux non admis300                description=" ".join(desc_bits),301                amenities=amenities,302                details=details,303                images=images,304            )305
Files main
Menu

Theme