SPB Git

Repository Public

base.py 9.1 KB 230 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/mortgage/providers/base.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-2413# Last Modified    : 2026-08-2414#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# mortgage/providers/base.py : classe de base des connecteurs de taux.91#   Contrat : fetch() retourne la liste des produits NORMALISÉS de92#   l'institution (dicts au format de make_product). Aucune écriture BD ici —93#   le scheduler valide puis enregistre. Jamais de taux inventé : un produit94#   non confirmé est simplement omis.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import os99import re100import time101102import requests103104USER_AGENT = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "105              "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36 "106              "ImmoKaBot/1.0 (+https://www.immo-ka.com/bot; contact@spboucher.ai)")107108SCRAPFLY_API = "https://api.scrapfly.io/scrape"109110111class RateProvider:112    provider_id: str = ""          # slug (rbc, td, desjardins…)113    institution: str = ""          # nom d'affichage114    source_url: str = ""           # page officielle des taux (lien public)115    request_delay: float = 1.0     # politesse116    timeout: int = 30117118    def __init__(self) -> None:119        self.session = requests.Session()120        self.session.headers["User-Agent"] = USER_AGENT121        self._last_request = 0.0122123    # -- backends -------------------------------------------------------------124    def get(self, url: str, **kw) -> requests.Response:125        wait = self.request_delay - (time.time() - self._last_request)126        if wait > 0:127            time.sleep(wait)128        resp = self.session.get(url, timeout=self.timeout, **kw)129        self._last_request = time.time()130        resp.raise_for_status()131        return resp132133    def get_scrapfly(self, url: str, render_js: bool = False,134                     asp: bool = True, country: str = "ca") -> str:135        """HTML via Firecrawl d'abord, puis Scrapfly (anti-bot) — dernier136        recours seulement."""137        from ...connectors import _resilient138        wait = self.request_delay - (time.time() - self._last_request)139        if wait > 0:140            time.sleep(wait)141        fc = _resilient.firecrawl_first(url, timeout=self.timeout,142                                        country=country, render_js=render_js)143        self._last_request = time.time()144        if fc is not None:145            return fc.text146        key = os.environ.get("SCRAPFLY_KEY") or os.environ.get("SCRAPFLY_API_KEY")147        if not key:148            raise RuntimeError("SCRAPFLY_KEY manquant (voir .env)")149        params: dict = {"key": key, "url": url, "country": country}150        if asp:151            params["asp"] = "true"152        if render_js:153            params["render_js"] = "true"154        wait = self.request_delay - (time.time() - self._last_request)155        if wait > 0:156            time.sleep(wait)157        resp = requests.get(SCRAPFLY_API, params=params, timeout=180)158        self._last_request = time.time()159        try:160            return (resp.json().get("result") or {}).get("content") or ""161        except ValueError:162            return ""163164    # -- normalisation --------------------------------------------------------165    def make_product(self, *, rate: float, rate_type: str, term_months: int,166                     kind: str, product_name: str | None = None,167                     apr: float | None = None,168                     insured_status: str = "unknown",169                     purpose: str = "purchase",170                     amortization_max_years: int | None = None,171                     conditions: str | None = None,172                     source_url: str | None = None,173                     confidence: float = 1.0,174                     raw=None) -> dict:175        """Observation normalisée commune à tous les providers."""176        return {177            "provider": self.provider_id,178            "institution": self.institution,179            "product_name": product_name,180            "rate_type": rate_type,181            "term_months": int(term_months),182            "kind": kind,183            "rate": round(float(rate), 4),184            "apr": round(float(apr), 4) if apr is not None else None,185            "insured_status": insured_status,186            "purpose": purpose,187            "amortization_max_years": amortization_max_years,188            "conditions": conditions,189            "source_url": source_url or self.source_url,190            "confidence": confidence,191            "raw": raw,192        }193194    # -- contrat --------------------------------------------------------------195    def fetch(self) -> list[dict]:196        raise NotImplementedError197198    # Point d'entrée pour les tests avec fixtures : si le provider parse un199    # payload texte, il expose parse(payload) et fetch() = parse(download()).200    def parse(self, payload: str) -> list[dict]:  # pragma: no cover201        raise NotImplementedError202203204def parse_rate(text: str) -> float | None:205    """Extrait un taux en % d'un texte : '4,19 %', '4.19%', ' 4.19 '.206    Retourne None si introuvable — jamais de valeur devinée."""207    if text is None:208        return None209    m = re.search(r"(\d{1,2}(?:[.,]\d{1,4})?)\s*%?", str(text).strip())210    if not m:211        return None212    try:213        return float(m.group(1).replace(",", "."))214    except ValueError:215        return None216217218def term_to_months(text: str) -> int | None:219    """'5 ans', '5 year', '5-year', '6 months', '6 mois' → mois."""220    if not text:221        return None222    t = str(text).lower()223    m = re.search(r"(\d{1,3})\s*(?:-|\s)?\s*(an|ans|année|year|yr)", t)224    if m:225        return int(m.group(1)) * 12226    m = re.search(r"(\d{1,3})\s*(?:-|\s)?\s*(mois|month)", t)227    if m:228        return int(m.group(1))229    return None230
Files main
Menu

Theme