SPB Git

Repository Public

samcon.py 9.3 KB 222 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/samcon.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/samcon.py : connecteur Samcon (samcon.ca) — condos LOCATIFS91#   seulement (section « Projects for rent » ; les projets en vente sont92#   exclus). Le site WordPress liste les immeubles locatifs sur93#   /projects-for-rent/ ; chaque fiche projet embarque le widget Planpoint94#   (app.planpoint.io/samcon/<hostName>). On rejoue l'API officielle du widget95#   POST https://app.planpoint.io/api/projects/find {namespace, hostName}96#   (HTTP 201) qui retourne le projet complet : adresse, GPS, étages et unités97#   {name, bedrooms « 1 bedroom », price, squareFeet, availability, images…}.98#   Seules les unités « Available » sont retenues (« Sold » = louée).99#   Une annonce par unité disponible ; external_id = <hostName>-<no d'unité>.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type108from .base import BaseConnector109110BASE = "https://www.samcon.ca"111RENT_URL = f"{BASE}/projects-for-rent/"112PLANPOINT_API = "https://app.planpoint.io/api/projects/find"113114HOST_RE = re.compile(r"app\.planpoint\.io/samcon/([\w-]+)")115116117class SamconConnector(BaseConnector):118    source_id = "samcon"119    request_delay = 0.8120121    def fetch(self) -> list[Listing]:122        html = self.get(RENT_URL).text123        soup = BeautifulSoup(html, "html.parser")124        main = soup.find("main") or soup125        # fiches projets locatifs (cartes de la page « Projects for rent »)126        projects = {}                    # url fiche -> nom affiché127        for a in main.find_all("a", href=True):128            href = a["href"]129            text = a.get_text(" ", strip=True)130            if "samcon.ca" not in href or not text \131                    or text.lower() == "view more details":132                continue133            projects.setdefault(href, text)134135        listings: list[Listing] = []136        for page_url, page_name in projects.items():137            try:138                page = self.get(page_url).text139            except Exception:140                continue141            m = HOST_RE.search(page)142            if not m:                    # pas de widget Planpoint : ignorer143                continue144            try:145                listings.extend(self._project(m.group(1), page_url, page_name))146            except Exception:147                continue148        return listings149150    def _project(self, host: str, page_url: str,151                 page_name: str) -> list[Listing]:152        resp = self.post(PLANPOINT_API, json={"namespace": "samcon",153                                              "hostName": host})154        proj = resp.json()155        if isinstance(proj, list):156            proj = proj[0] if proj else {}157        name = (proj.get("name") or page_name).strip()158        address = (proj.get("address") or "").replace(", Canada", "").strip()159        try:160            lat = float(proj["lat"]) if proj.get("lat") else None161            lng = float(proj["lon"]) if proj.get("lon") else None162        except (TypeError, ValueError):163            lat = lng = None164        proj_images = [u for u in (proj.get("images") or [])165                       if isinstance(u, str) and u.startswith("http")]166167        listings: list[Listing] = []168        for floor in proj.get("floors") or []:169            floor_name = (floor.get("name") or "").strip()170            for u in floor.get("units") or []:171                if (u.get("availability") or "").strip() != "Available":172                    continue             # « Sold » = unité louée173                unum = str(u.get("name") or u.get("_id") or "").strip()174                if not unum:175                    continue176                bed_raw = (u.get("bedrooms") or "").strip()177                price = u.get("price")178                try:179                    price = float(price) if price else None180                except (TypeError, ValueError):181                    price = None182                area = None183                try:184                    area = float(u["squareFeet"]) if u.get("squareFeet") \185                        else None186                except (TypeError, ValueError):187                    pass188                images = [i for i in (u.get("images") or [])189                          if isinstance(i, str) and i.startswith("http")] \190                    or proj_images191                amenities = [str(x).strip() for x in192                             (u.get("inclusionsArr") or []) if x]193                if floor_name:194                    amenities.append(f"Étage : {floor_name}")195                furnished = u.get("furnished") \196                    if isinstance(u.get("furnished"), bool) else None197                avail = "Disponible"198                if (u.get("deliveryDate") or "").strip():199                    avail = f"Disponible {u['deliveryDate'].strip()}"200                listings.append(Listing(201                    source=self.source_id,202                    external_id=f"{host}-{unum}",203                    url=page_url,204                    title=f"{name} — {bed_raw or 'unité'} · unité {unum}",205                    address=address,206                    sector="",207                    city="Montréal",208                    unit_type=normalize_unit_type(bed_raw),209                    price=price,210                    price_label=f"{price:.0f} $" if price else "",211                    availability=avail,212                    area_sqft=area,213                    furnished=furnished,214                    description=(u.get("description") or "").strip()215                    if isinstance(u.get("description"), str) else "",216                    amenities=amenities,217                    images=images[:12],218                    lat=lat,219                    lng=lng,220                ))221        return listings222
Files main
Menu

Theme