SPB Git

Repository Public

quality.py 14.7 KB 364 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/quality.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-2714#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# quality.py : score de complétude par annonce + seuil minimum de publication91#   Une annonce sous le seuil (sans prix, sans localisation ou sans contenu92#   exploitable) est mise en QUARANTAINE (published=0) : conservée en base,93#   re-synchronisée normalement, mais jamais affichée sur le site.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import json98import os99import re100101# Seuil de publication (score 0–100). Les portes dures (prix, localisation,102# contenu) s'appliquent en plus du score — voir evaluate().103PUBLISH_THRESHOLD = 40104105# Pondération du score de complétude (total = 100)106W_PRICE = 20         # prix mensuel exploitable107W_LOCATION = 14      # adresse OU coordonnées GPS (partiel si ville seulement)108W_CITY = 4109W_DESCRIPTION = 14   # >= 200 caractères ; partiel si >= 60110W_IMAGES = 16        # 0 -> 0 ; 1 -> 6 ; 2-4 -> 11 ; >= 5 -> 16111W_UNIT = 8           # type d'unité ou nombre de chambres112W_AVAILABILITY = 5113W_AREA = 4114W_BATHROOMS = 3115W_AMENITIES = 5      # >= 3 commodités ; partiel si >= 1116W_DETAILS = 4        # >= 3 champs structurés117W_URL = 3            # lien vers l'annonce originale (contact / réservation)118119120# ---- pertinence : n'afficher que des LOGEMENTS à louer au mois --------------121# Certaines sources mêlent stationnements, garages, entreposage, locaux122# commerciaux, objets divers ou locations à la nuit — souvent à ~200 $/mois.123# Ces annonces passent le score de complétude mais ne sont pas des logements :124# on les met en quarantaine (published=0) avec une raison « hors sujet ».125126# vocabulaire logement (titre/description) — inclut les termes anglais du127# marché ontarien (expansion 2026-08) : un logement ON légitime ne doit128# jamais tomber en quarantaine « hors sujet » faute de vocabulaire129_RE_RES = re.compile(130    r"chambre|room|studio|appart|apartment|condo|loft|maison|house|"131    r"logement|logis\b|r[ée]sidences?\b|chalet|penthouse|duplex|triplex|"132    r"bachelor|colocation|townhouses?|bungalows?|"133    r"sous-sol|basement|½|1/2|\b\d[.,]5\b|\bdemie?s?\b|\bbed(?:room)?s?\b|"134    r"\bunit[ée]?s?\b|\bpi[eè]ces\b", re.I)135136# objet non résidentiel proposé à la location137_RE_NONRES = re.compile(138    r"stationnements?|parkings?|garages?|entrep[oô]ts?|entreposage|"139    r"espaces? de rangement|places? de (?:stationnement|parking)|"140    r"lockers?|cabanons?|remises?|"141    r"loca(?:l|ux) commercia(?:l|ux)|espaces? commercia(?:l|ux)|\bbureaux?\b",142    re.I)143144# description qui COMMENCE par l'objet non résidentiel (l'annonce vend ça)145_RE_DESC_LEAD = re.compile(146    r"^\W*(?:grande?s?|petite?s?|beaux?|belles?|beau|magnifiques?|superbes?|"147    r"jolie?s?|\d+)?\s*"148    r"(?:stationnements?|parkings?|garages?|entrep[oô]ts?|"149    r"places? de (?:stationnement|parking)|espaces? de (?:rangement|stationnement)|"150    r"bureaux?|loca(?:l|ux) (?:commercia(?:l|ux)|industriels?|professionnels?))\b",151    re.I)152153# local commercial / bureau / industriel (titre ou description)154_RE_COMMERCIAL = re.compile(155    r"loca(?:l|ux)\s+(?:commercia(?:l|ux)|industriels?|professionnels?)|"156    r"espaces?\s+(?:de\s+)?bureaux?\b|espaces?\s+commercia(?:l|ux)|"157    r"aménagé\s+en\s+(?:restaurant|commerce|boutique)|"158    r"(?:usage|zonage|bail)\s+commercial", re.I)159160# « bureau » comme nom de rue (av. Jacques-Bureau…) — pas un local à louer161_RE_STREET_BUREAU = re.compile(162    r"(?:av(?:enue)?|rue|boul(?:evard)?|ch(?:emin)?|pl(?:ace)?)\.?\s+"163    r"(?:\w+[- ])?bureau\b", re.I)164165# location à la nuit / courte durée (le « loyer » n'est pas un prix mensuel)166_RE_NIGHTLY = re.compile(167    r"tarif par nuit|prix par nuit|par nuit et non par mois|"168    r"location à la nuit|court terme seulement", re.I)169170171def relevance_reason(d: dict) -> str | None:172    """Retourne la raison de quarantaine si l'annonce n'est pas un logement173    à louer au mois (stationnement, garage, entreposage, local commercial,174    objet divers, location à la nuit), sinon None.175176    Les seuils de prix évitent les faux positifs : un vrai logement dont le177    titre mentionne « garage » (ex. « Garage intérieur chauffé » pour un 4½178    à 2 250 $) reste publié, alors qu'un « garage à louer » à 195 $ tombe.179    """180    title = (d.get("title") or "").strip()181    desc = (d.get("description") or "").strip()182    head = desc[:300]183    price = d.get("price")184    priced = isinstance(price, (int, float))185    unit = (d.get("unit_type") or "").strip()186    res_title = bool(_RE_RES.search(title))187    res_text = res_title or bool(_RE_RES.search(head))188189    # 1) le titre vend un stationnement/garage/local, sans vocabulaire logement190    if _RE_NONRES.search(title) and not res_title \191            and not _RE_STREET_BUREAU.search(title) \192            and (not unit or not priced or price < 700):193        return "hors sujet : stationnement/garage/local (titre)"194    # 2) la description s'ouvre sur l'objet non résidentiel — attrape les195    #    titres trompeurs (« Appartement Garage à Louer » à 195 $) et les196    #    titres-adresses (« P158 1400 Boul René-Lévesque »)197    if _RE_DESC_LEAD.match(desc) and (198            not priced or price < 450199            or (not res_title and "à vendre" in head.lower())):200        return "hors sujet : stationnement/garage/local (description)"201    # 3) prix de case de stationnement + aucun vocabulaire logement202    if priced and price < 450 and not res_text and _RE_NONRES.search(head):203        return "hors sujet : stationnement/garage (prix + texte)"204    # 4) local commercial/bureau/industriel sans aucun vocabulaire logement205    if not res_text and _RE_COMMERCIAL.search(f"{title}\n{head}"):206        return "hors sujet : local commercial/bureau"207    # 5) prix impossible pour un logement + aucun signal logement dans le texte208    #    (case de stationnement à titre-adresse, objets divers…)209    if priced and price < 300 and not res_text and unit != "Chambre":210        return "hors sujet : prix non résidentiel, aucun signal logement"211    # 6) prix à la nuit / courte durée affiché comme loyer mensuel212    if priced and price < 600 and _RE_NIGHTLY.search(desc):213        return "hors sujet : location à la nuit / court terme"214    return None215216217def _as_list(value) -> list:218    if isinstance(value, list):219        return value220    if isinstance(value, str) and value:221        try:222            out = json.loads(value)223            return out if isinstance(out, list) else []224        except ValueError:225            return []226    return []227228229def _as_dict(value) -> dict:230    if isinstance(value, dict):231        return value232    if isinstance(value, str) and value:233        try:234            out = json.loads(value)235            return out if isinstance(out, dict) else {}236        except ValueError:237            return {}238    return {}239240241def evaluate(d: dict) -> tuple[float, bool, list[str]]:242    """Évalue une annonce (dict aux clés du schéma listings).243244    Retourne (score 0–100, publiable, raisons de quarantaine).245    Accepte indifféremment les champs JSON sérialisés (rangée SQLite) ou246    déjà décodés (Listing.asdict) — images/amenities/details.247    """248    score = 0.0249    reasons: list[str] = []250251    # PAUSE ONTARIO (2026-08-27) : l'expansion ON est suspendue — les annonces252    # ON restent en base et re-synchronisables, mais partent en quarantaine253    # tant que LOUKA_ONTARIO=1 n'est pas reposé dans .env254    # (voir docs/ONTARIO-PAUSE.md ; réactivation : flag + `run.py quality`).255    if d.get("province") == "ON" and os.environ.get("LOUKA_ONTARIO") != "1":256        reasons.append("pause-ontario")257258    # loyer mensuel plausible : hors bornes = donnée corrompue à la source259    # (0,02 $, 1 $, prix « à la nuit »…) — traité comme absence de prix260    price = d.get("price")261    has_price = isinstance(price, (int, float)) and 175 <= price <= 20000262    if has_price:263        score += W_PRICE264265    address = (d.get("address") or "").strip()266    city = (d.get("city") or "").strip()267    sector = (d.get("sector") or "").strip()268    has_coords = d.get("lat") is not None and d.get("lng") is not None269    if address or has_coords:270        score += W_LOCATION271    elif sector:272        score += W_LOCATION * 0.5273    if city:274        score += W_CITY275276    desc = (d.get("description") or "").strip()277    if len(desc) >= 200:278        score += W_DESCRIPTION279    elif len(desc) >= 60:280        score += W_DESCRIPTION * 0.5281282    images = _as_list(d.get("images"))283    n_img = len(images)284    if n_img >= 5:285        score += W_IMAGES286    elif n_img >= 2:287        score += 11288    elif n_img == 1:289        score += 6290291    if (d.get("unit_type") or "").strip() or d.get("bedrooms") is not None:292        score += W_UNIT293    if d.get("availability_date") or (d.get("availability") or "").strip():294        score += W_AVAILABILITY295    if d.get("area_sqft"):296        score += W_AREA297    if d.get("bathrooms") is not None:298        score += W_BATHROOMS299300    amenities = _as_list(d.get("amenities"))301    if len(amenities) >= 3:302        score += W_AMENITIES303    elif len(amenities) >= 1:304        score += W_AMENITIES * 0.5305306    details = _as_dict(d.get("details"))307    if len(details) >= 3:308        score += W_DETAILS309    elif len(details) >= 1:310        score += W_DETAILS * 0.5311312    if (d.get("url") or "").strip():313        score += W_URL314315    score = round(min(score, 100.0), 1)316317    # ---- portes dures de publication ---------------------------------------318    if not has_price:319        reasons.append("sans prix" if not price else f"prix non plausible ({price:g} $)")320    if not (address or has_coords or city):321        reasons.append("sans localisation")322    # contenu exploitable : description OU un minimum de structure323    if len(desc) < 40 and not amenities and not (d.get("unit_type") or "").strip() \324            and d.get("bedrooms") is None:325        reasons.append("sans contenu exploitable")326    # pertinence : pas un logement à louer au mois (stationnement, garage…)327    rel = relevance_reason(d)328    if rel:329        reasons.append(rel)330    if not reasons and score < PUBLISH_THRESHOLD:331        reasons.append(f"complétude {score:.0f} < seuil {PUBLISH_THRESHOLD}")332333    return score, not reasons, reasons334335336def backfill(limit: int | None = None, verbose: bool = True) -> dict:337    """(Re)calcule completeness/published sur toutes les annonces actives."""338    from . import db339    con = db.connect()340    rows = con.execute(341        "SELECT uid, title, price, address, city, sector, lat, lng, description,"342        " images, unit_type, bedrooms, bathrooms, availability,"343        " availability_date, area_sqft, amenities, details, url, province"344        " FROM listings WHERE active=1"345        + (f" LIMIT {int(limit)}" if limit else "")).fetchall()346    pub = quar = 0347    for r in rows:348        score, ok, reasons = evaluate(dict(r))349        con.execute(350            "UPDATE listings SET completeness=?, published=?, quality_reasons=?"351            " WHERE uid=?",352            (score, int(ok), json.dumps(reasons, ensure_ascii=False) if reasons353             else None, r["uid"]))354        if ok:355            pub += 1356        else:357            quar += 1358    con.commit()359    con.close()360    out = {"evaluees": len(rows), "publiees": pub, "quarantaine": quar}361    if verbose:362        print(f"[lou-ka] quality: {out}")363    return out364
Files main
Menu

Theme