SPB Git

Repository Public

validate.py 10.8 KB 256 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : KA Enrich7# File             : kaenrich/validate.py8# Module           : Kaenrich9# Repository       : https://git.spboucher.ai/ka-enrich10# Project Website  : Not specified11# Created          : 2026-12-0312# Last Modified    : 2026-12-0313#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Validation des réponses du modèle : aucune valeur sans preuve dans le texte.4243Trois barrières, dans l'ordre :441. la citation doit se retrouver dans l'annonce (comparaison sans accents,45   casse ni ponctuation) ;462. la valeur doit être plausible pour le champ (bornes) ;473. pour les champs chiffrés, le nombre doit apparaître dans la citation48   (ou s'en déduire par une conversion connue), et pour quelques champs49   la citation doit contenir un mot du sujet (« animaux », « meublé »…).504. `refine.py` relit la citation et corrige ou rejette le classement51   (stationnement avec un prix rendu « inclus », une seule espèce refusée52   rendue « animaux refusés », étage sans numéro…).5354Une valeur rejetée est simplement absente du résultat ; le motif est compté.55"""56from __future__ import annotations5758import datetime as _dt59import re60import unicodedata6162from .refine import refine63from .spec import PROFILES6465_WORD_NUM = {66    "un": 1, "une": 1, "one": 1, "deux": 2, "two": 2, "trois": 3, "three": 3,67    "quatre": 4, "four": 4, "cinq": 5, "five": 5, "six": 6, "sept": 7,68    "seven": 7, "huit": 8, "eight": 8, "neuf": 9, "nine": 9, "dix": 10,69    "ten": 10, "douze": 12, "twelve": 12,70}717273def fold(s: str) -> str:74    """Minuscules, sans accents, ponctuation et espaces réduits."""75    s = unicodedata.normalize("NFKD", s or "")76    s = "".join(c for c in s if not unicodedata.combining(c)).lower()77    s = s.replace("œ", "oe").replace("æ", "ae")78    return re.sub(r"[^a-z0-9$½]+", " ", s).strip()798081def numbers_in(q: str) -> list[float]:82    """Nombres écrits dans la citation (« 1 200 », « 1,5 », « 850 », « deux »)."""83    out: list[float] = []84    t = (q or "").replace(" ", " ").replace(" ", " ")85    for m in re.finditer(r"\d[\d ,.']*\d|\d", t):86        raw = m.group(0)87        cands = set()88        compact = re.sub(r"[ ']", "", raw)89        # 1,200 / 1.200 = séparateur de milliers ; 1,5 / 1.5 = décimale90        if re.fullmatch(r"\d{1,3}([,.]\d{3})+", compact):91            cands.add(float(re.sub(r"[,.]", "", compact)))92        else:93            try:94                cands.add(float(compact.replace(",", ".")))95            except ValueError:96                pass97            if "," in compact or "." in compact:98                try:99                    cands.add(float(re.sub(r"[,.]", "", compact)))100                except ValueError:101                    pass102        out.extend(sorted(cands))103    for w in fold(q).split():104        if w in _WORD_NUM:105            out.append(float(_WORD_NUM[w]))106    return out107108109def _near(a: float, b: float, tol: float = 0.01) -> bool:110    return abs(a - b) <= max(tol * abs(b), 0.51 if b >= 10 else 0.01)111112113# conversions admises entre le nombre cité et la valeur rendue114_AREA_FACTORS = (1.0, 10.7639)                       # pi², m²115_LOT_FACTORS = (1.0, 10.7639, 43560.0, 107639.0)     # pi², m², acre, hectare116117# (min, max) plausibles118_BOUNDS = {119    "area_sqft": (80, 20000), "lot_sqft": (200, 5e8), "bathrooms": (0.5, 12),120    "bedrooms": (0, 20), "powder_rooms": (0, 10), "garage": (0, 12),121    "parking": (0, 60), "parking_price": (10, 1000), "floor": (-1, 60),122    "lease_min_months": (1, 36), "municipal_tax": (50, 500000),123    "school_tax": (10, 100000), "condo_fees": (10, 5000), "units": (1, 500),124    "gross_revenue": (1000, 5e7),125}126127# mots dont l'un doit figurer dans la citation (texte replié)128_TOPIC = {129    "pets": r"anima|chat|chien|pet|dog|cat\b",130    "furnished": r"meubl|furnish",131    "smoking": r"fume|fumeu|smok|tabac|cannabis|vapot",132    "parking": r"stationnement|parking|garage|driveway|entree",133    "parking_price": r"stationnement|parking|garage",134    "deposit": r"depot|deposit|premier mois|dernier mois|first month|last month",135    "credit_check": r"credit",136    "references": r"reference|preuve|proof|revenu|income|emploi",137    "insurance": r"assurance|insurance",138    "lease_min_months": r"bail|lease|mois|month|an\b|year|terme",139    "floor": r"etage|floor|rez|sous sol|basement|niveau|rdc|demi",140    "bathrooms": r"salle|bain|sdb|bath|eau|toilet",141    "powder_rooms": r"salle d eau|powder|half bath|toilet",142    "construction_year": r"constru|bati|built|annee|neuf|neuve|19\d\d|20\d\d",143    "year_built": r"constru|bati|built|annee|neuf|neuve|19\d\d|20\d\d",144    "area_sqft": r"pi|p2|pc|sq|ft|m2|metre|superficie|habitable",145    "lot_sqft": r"terrain|lot|acre|hectare|arpent|land",146    "municipal_tax": r"municipal|taxe|tax",147    "school_tax": r"scolaire|school",148    "condo_fees": r"copropriete|condo|frais|fees",149    "units": r"logement|unite|unit|plex|appartement|porte",150    "gross_revenue": r"revenu|income|loyer|rent",151    "pool": r"piscine|pool",152    "basement": r"sous sol|basement",153    "waterfront": r"bord|riverain|lac|riviere|fleuve|water|lake|river",154    "garage": r"garage",155    "bedrooms": r"chambre|cac|bedroom|\bbr\b|c c",156    "availability": r"dispon|libre|avail|immediat|maintenant|occupation|"157                    r"janvier|fevrier|mars|avril|mai|juin|juillet|aout|"158                    r"septembre|octobre|novembre|decembre|january|february|"159                    r"march|april|may|june|july|august|september|october|"160                    r"november|december|\d{4} \d{2} \d{2}|\d{1,2} \d{1,2} \d{2,4}",161}162163_NUMERIC = ("area_sqft", "lot_sqft", "bathrooms", "bedrooms", "powder_rooms",164            "garage", "parking_price", "lease_min_months", "municipal_tax",165            "school_tax", "condo_fees", "units", "gross_revenue",166            "construction_year", "year_built")167168169def _check_number(field: str, v: float, q: str) -> str | None:170    nums = numbers_in(q)171    if field == "area_sqft":172        ok = any(_near(v, n * f) for n in nums for f in _AREA_FACTORS)173    elif field == "lot_sqft":174        ok = any(_near(v, n * f) for n in nums for f in _LOT_FACTORS)175    elif field == "lease_min_months":176        fq = fold(q)177        ok = any(_near(v, n) for n in nums) or \178            any(_near(v, 12 * n) for n in nums) or \179            (v == 12 and re.search(r"\b(un an|1 an|annuel|one year|yearly)\b", fq) is not None)180    elif field == "bathrooms":181        # « 1 salle de bain et 1 salle d'eau » -> 1.5 : somme admise182        ok = any(_near(v, n) for n in nums) or \183            any(_near(v, a + 0.5 * b) for a in nums for b in nums) or \184            (v in (1, 1.0) and not nums)       # « une salle de bain complète »185    elif field in ("bedrooms", "powder_rooms", "garage", "units"):186        ok = any(_near(v, n) for n in nums) or (v == 1 and not nums)187    else:188        ok = any(_near(v, n) for n in nums)189    return None if ok else "nombre_absent_de_la_citation"190191192def validate(profile: str, text: str, answer: dict, today: str | None = None) -> tuple[dict, dict]:193    """Retourne (faits retenus, rejets). `faits[champ] = {"v":…, "q":…}`."""194    spec = PROFILES[profile]195    folded_text = fold(text)196    kept: dict = {}197    rejected: dict = {}198    year_now = int((today or _dt.date.today().isoformat())[:4])199    for field in spec:200        item = answer.get(field) if isinstance(answer, dict) else None201        if item is None:202            continue203        if not isinstance(item, dict) or "v" not in item or not isinstance(item.get("q"), str):204            rejected[field] = "forme"205            continue206        v, q = item["v"], item["q"].strip()207        fq = fold(q)208        if len(fq) < 3 or fq not in folded_text:209            rejected[field] = "citation_introuvable"210            continue211        topic = _TOPIC.get(field)212        if topic and not re.search(topic, fq):213            rejected[field] = "citation_hors_sujet"214            continue215        if field in ("construction_year", "year_built") \216                and re.search(r"renov|refait|restaur|update|refurb", fq) \217                and not re.search(r"constru|bati|built", fq):218            rejected[field] = "annee_de_renovation"219            continue220        if v is None or v == "":221            continue222        if isinstance(v, bool):223            if v is False and field in ("credit_check", "references", "insurance", "waterfront"):224                continue                      # « non exigé » : rien à afficher225        elif isinstance(v, (int, float)):226            lo, hi = _BOUNDS.get(field, (None, None))227            if field in ("construction_year", "year_built"):228                lo, hi = 1700, year_now + 3229            if lo is not None and not (lo <= v <= hi):230                rejected[field] = "hors_bornes"231                continue232            if field in _NUMERIC and field not in ("floor", "area_sqft"):233                why = _check_number(field, float(v), q)234                if why:235                    rejected[field] = why236                    continue237        if field == "availability" and v != "now":238            try:239                d = _dt.date.fromisoformat(v)240            except (TypeError, ValueError):241                rejected[field] = "date_invalide"242                continue243            ref = _dt.date.fromisoformat(today) if today else _dt.date.today()244            if d < ref - _dt.timedelta(days=45) or d > ref + _dt.timedelta(days=550):245                rejected[field] = "date_hors_fenetre"246                continue247            if not re.search(r"\d", q):248                rejected[field] = "date_sans_chiffre"249                continue250        v, why = refine(field, v, q, fq, numbers_in(q))251        if why:252            rejected[field] = why253            continue254        kept[field] = {"v": v, "q": q}255    return kept, rejected256
Files main
Menu

Theme