SPB Git

Repository Public

cosoltec.py 13.0 KB 282 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/cosoltec.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/cosoltec.py : connecteur Cosoltec (cosoltec.com — projets locatifs91#   Evado à Sainte-Thérèse, Le Monroe à Blainville, Natür à Saint-Jérôme).92#   Les sites vitrines (evado.ca, lemonroe.ca, naturcondos.ca) affichent leurs93#   unités via le widget Planpoint : on interroge la même API JSON publique94#   (app.planpoint.io/api/{groups,projects}/find, POST namespace+hostName,95#   3 requêtes/sync) — prix mensuel, pi², chambres, statut, plans et photos96#   par unité, inclusions (inclusionsArr, clé « fr »), date de livraison et97#   galerie du projet ; seules les unités « Available » sont retenues.98#   Les unités Natür n'ont AUCUN prix chez la source (price null, le site99#   n'en affiche pas non plus) — rien d'inventé. La description est composée100#   du texte de présentation de la vitrine (meta description + 1er paragraphe,101#   1 requête par vitrine) et des faits structurés de l'unité.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106import time107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type111from .base import BaseConnector112113PLANPOINT_API = "https://app.planpoint.io/api"114115# les trois vitrines locatives de Cosoltec branchées sur Planpoint116_SITES = [117    {"kind": "groups", "namespace": "evado", "hostName": "evado",118     "page": "https://www.evado.ca/plans", "home": "https://www.evado.ca/",119     "city": "Sainte-Thérèse"},120    {"kind": "groups", "namespace": "monroe", "hostName": "monroe",121     "page": "https://www.lemonroe.ca/plans", "home": "https://www.lemonroe.ca/",122     "city": "Blainville"},123    {"kind": "projects", "namespace": "cosolte", "hostName": "Natur",124     "page": "https://www.naturcondos.ca/", "home": "https://www.naturcondos.ca/",125     "city": "Saint-Jérôme"},126]127128129class CosoltecConnector(BaseConnector):130    source_id = "cosoltec"131    request_delay = 0.8132    max_pages = 3        # 1 appel API par vitrine (evado, monroe, natur)133134    # -- POST poli (même throttling/session que get(), donc record/replay ok) --135    def _post_json(self, url: str, payload: dict) -> dict:136        wait = self.request_delay - (time.time() - self._last_request)137        if wait > 0:138            time.sleep(wait)139        resp = self.session.post(url, json=payload, timeout=self.timeout)140        self._last_request = time.time()141        resp.raise_for_status()142        return resp.json()143144    # -- texte de présentation de la vitrine (meta + 1er paragraphe long) ------145    def _site_blurb(self, site: dict) -> str:146        try:147            soup = BeautifulSoup(self.get(site["home"]).text, "html.parser")148        except Exception:149            return ""150        parts: list[str] = []151        meta = (soup.select_one('meta[name="description"][content]')152                or soup.select_one('meta[property="og:description"][content]'))153        if meta and meta.get("content"):154            parts.append(re.sub(r"\s+", " ", meta["content"]).strip())155        for p in soup.find_all("p"):156            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))157            if len(t) > 120:158                if t not in parts:159                    parts.append(t)160                break161        return " ".join(parts)[:900]162163    def fetch(self) -> list[Listing]:164        listings: list[Listing] = []165        for site in _SITES:166            try:167                data = self._post_json(168                    f"{PLANPOINT_API}/{site['kind']}/find",169                    {"namespace": site["namespace"], "hostName": site["hostName"]})170            except Exception:171                continue172            site = dict(site, blurb=self._site_blurb(site))173            # groups/find -> {projects: [...]} ; projects/find -> un seul projet174            projects = data.get("projects") if site["kind"] == "groups" else [data]175            # adresse de repli : celle d'une phase sœur du même complexe176            # (ex. « Le Monroe 1 » n'a pas d'adresse, « Le Monroe 2 » oui)177            sibling = next((p.get("address") for p in projects or []178                            if (p.get("address") or "").strip()), "")179            site["sibling_address"] = sibling180            for project in projects or []:181                listings.extend(self._parse_project(project, site))182        return listings183184    # -- un projet Planpoint = un immeuble ---------------------------------------185    def _parse_project(self, project: dict, site: dict) -> list[Listing]:186        name = (project.get("name") or "").strip()187        # adresse « 350 Place Fabien-Drapeau, Sainte-Thérèse, Quebec J7E 0C4 »188        raw_addr = (project.get("address") or "").strip() \189            or site.get("sibling_address", "")190        addr_parts = [p.strip() for p in raw_addr.split(",") if p.strip()]191        street = addr_parts[0] if addr_parts else ""192        city = addr_parts[1] if len(addr_parts) > 1 else site["city"]193        lat = project.get("lat")194        lng = project.get("lon")195196        # galerie du projet (photos communes) : ajoutée après celles de l'unité197        proj_imgs = [i for i in (project.get("images") or [])198                     if isinstance(i, str) and i.startswith("http")]199        cover = project.get("projectImageUrl")200        if isinstance(cover, str) and cover.startswith("http") \201                and cover not in proj_imgs:202            proj_imgs.append(cover)203204        res: list[Listing] = []205        for floor in project.get("floors") or []:206            for u in floor.get("units") or []:207                # seules les unités affichées « Disponible » chez la source208                if (u.get("availability") or "").lower() != "available":209                    continue210                uid = u.get("_id") or ""211                if not uid:212                    continue213                price = u.get("price")214                price = float(price) if isinstance(price, (int, float)) and price > 0 else None215                area = u.get("squareFeet")216                area = float(area) if isinstance(area, (int, float)) and area > 0 else None217                images = [i for i in (u.get("images") or []) if isinstance(i, str)]218                images += [i for i in (u.get("layoutGallery") or [])219                           if isinstance(i, str) and i not in images]220                images += [i for i in proj_imgs if i not in images]221                details: dict = {}222                if isinstance(u.get("bathrooms"), (int, float)):223                    details["bathrooms"] = u["bathrooms"]224                if floor.get("name"):225                    details["floor"] = floor["name"]226                # inclusions par unité (libellés français de l'API)227                amenities: list[str] = []228                for inc in u.get("inclusionsArr") or []:229                    lbl = (inc.get("fr") or inc.get("en") or "").strip() \230                        if isinstance(inc, dict) else str(inc).strip()231                    if lbl:232                        lbl = lbl[0].upper() + lbl[1:]233                        if lbl not in amenities:234                            amenities.append(lbl)235                # date de livraison structurée (« 2026-09-01T… »)236                delivery = str(u.get("deliveryDate") or "")[:10]237                availability = u.get("availability") or ""238                if delivery:239                    availability = f"Disponible le {delivery}"240                # description : présentation de la vitrine + faits de l'unité241                facts: list[str] = []242                if u.get("name"):243                    facts.append(f"Unité {u['name']} du projet {name}"244                                 f" à {city}.")245                bits = []246                if u.get("type"):247                    bits.append(f"modèle {u['type']}")248                if floor.get("name"):249                    bits.append(f"étage {floor['name']}")250                if area:251                    bits.append(f"{area:g} pi²")252                if isinstance(u.get("bathrooms"), (int, float)):253                    bits.append(f"{u['bathrooms']:g} salle(s) de bain")254                if bits:255                    facts.append(", ".join(bits).capitalize() + ".")256                if amenities:257                    facts.append("Inclusions : " + ", ".join(amenities) + ".")258                desc = " ".join(x for x in259                                [" ".join(facts), site.get("blurb", "")] if x)260                res.append(Listing(261                    source=self.source_id,262                    external_id=uid,             # ObjectId Planpoint de l'unité263                    url=site["page"],            # pas de page par unité publiée264                    title=f"{name} — Unité {u.get('name', '')}".strip(" —"),265                    address=street,266                    city=city,267                    unit_type=normalize_unit_type(u.get("bedrooms") or ""),268                    price=price,269                    price_label=f"{price:.0f} $ /mois" if price else "",270                    availability=availability,271                    availability_date=delivery or None,272                    area_sqft=area,273                    furnished=u["furnished"] if isinstance(u.get("furnished"), bool) else None,274                    description=desc[:2000],275                    amenities=amenities,276                    details=details,277                    images=images[:30],278                    lat=lat if (lat is not None and lng is not None) else None,279                    lng=lng if (lat is not None and lng is not None) else None,280                ))281        return res282
Files main
Menu

Theme