SPB Git

Repository Public

normalize.ts 21.6 KB 464 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : packages/engine/src/normalize.ts9 * Module           : engine10 * Repository       : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website  : https://jeux.uqo-eval.app12 * Created          : 2026-11-2513 * Last Modified    : 2026-11-2514 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Property Normalization Engine.45 *46 * Transforme une inscription brute en propriété normalisée, ou la rejette avec47 * un motif. Règle d'or : ne jamais inventer une caractéristique absente.48 */49import { municipalityByCode, municipalityByName, normalizeName, regionCodeFromLabel, regionName } from "./regions.ts";50import type {51  Assessment,52  Category,53  NormalizeResult,54  NormalizedProperty,55  PricePoint,56  RawListing,57  RawPricePoint,58} from "./types.ts";5960export interface NormalizeOptions {61  minPrice: number;62  maxPrice: number;63  minQualityScore: number;64  /** Sources de petites annonces exclues (données trop hétérogènes). */65  excludedSources: readonly string[];66  now: Date;67}6869export const DEFAULT_NORMALIZE_OPTIONS: Omit<NormalizeOptions, "now"> = {70  minPrice: 60_000,71  maxPrice: 15_000_000,72  minQualityScore: 70,73  excludedSources: ["fb_marketplace", "kijiji", "lespac"],74};7576type Details = Record<string, unknown>;7778function parseJson<T>(text: string | null, fallback: T): T {79  if (!text) return fallback;80  try {81    const value = JSON.parse(text) as unknown;82    return (value ?? fallback) as T;83  } catch {84    return fallback;85  }86}8788/** « 348 000 $ (2026) », « $ 956,400 », « 12 000,00 $ » → nombre de dollars. */89export function parseMoney(value: unknown): number | null {90  if (typeof value === "number") return Number.isFinite(value) ? value : null;91  if (typeof value !== "string") return null;92  const head = value.split("(")[0] ?? "";93  let s = head.replace(/[\s  $]/g, "").replace(/\/an|paran/gi, "");94  if (!/\d/.test(s)) return null;95  // « 2,5 M » ou « 1,2 million » : multiplicateur explicite96  const million = s.match(/^(\d+(?:[.,]\d+)?)(?:M|millions?)$/i);97  if (million) return Math.round(Number(million[1]!.replace(",", ".")) * 1_000_000);98  // décimales « ,5 », « ,00 » ou « .00 » en fin de chaîne99  s = s.replace(/[.,](\d{1,2})$/, "");100  s = s.replace(/[.,]/g, "");101  const n = Number(s.replace(/[^\d]/g, ""));102  return Number.isFinite(n) ? n : null;103}104105function parseYearIn(value: unknown): number | null {106  if (typeof value !== "string" && typeof value !== "number") return null;107  const m = String(value).match(/\b(19|20)\d{2}\b/);108  return m ? Number(m[0]) : null;109}110111function parseIntLoose(value: unknown): number | null {112  if (typeof value === "number") return Number.isFinite(value) ? Math.round(value) : null;113  if (typeof value !== "string") return null;114  const m = value.match(/\d+/);115  return m ? Number(m[0]) : null;116}117118function cleanText(value: unknown, max = 90): string | null {119  if (typeof value !== "string") return null;120  const s = value.replace(/\s+/g, " ").trim();121  if (!s || s.length > max || /\$|https?:|@/.test(s)) return null;122  return s;123}124125/** Première valeur parmi `keys` qui respecte le motif attendu (protège des champs mal aiguillés à la source). */126function pickField(details: Details, keys: readonly string[], pattern: RegExp): string | null {127  for (const key of keys) {128    const value = cleanText(details[key]);129    if (value && pattern.test(value)) return value;130  }131  return null;132}133134const NEGATIVE = /^(non|aucun|aucune|0|n\/a|sans)$/i;135136function toIsoDay(ts: number | null | undefined): string | null {137  if (!ts || !Number.isFinite(ts)) return null;138  return new Date(ts * 1000).toISOString().slice(0, 10);139}140141function resolveCategory(raw: RawListing, details: Details): { category: Category; subtype: string | null } | null {142  const type = (raw.property_type ?? "").trim();143  const hint = [details["Type de propriété"], details["Style de bâtiment"], details["Style"], details["Genre de propriété"]]144    .filter((v): v is string => typeof v === "string")145    .join(" | ");146  const h = normalizeName(hint);147  const houseSubtype = (): string | null => {148    if (/plain pied|bungalow/.test(h)) return "Plain-pied (bungalow)";149    if (/paliers/.test(h)) return "Paliers multiples";150    if (/etage et demi/.test(h)) return "Un étage et demi";151    if (/etages|cottage|2 etages/.test(h)) return "Maison à étages";152    return null;153  };154  switch (type) {155    case "Condo":156      return { category: "condo", subtype: /indivise/.test(h) ? "Copropriété indivise" : null };157    case "Duplex":158      return { category: "plex", subtype: "Duplex" };159    case "Triplex":160      return { category: "plex", subtype: "Triplex" };161    case "Multiplex":162      return { category: "plex", subtype: /quadruplex/.test(h) ? "Quadruplex" : "Multiplex" };163    case "Maison de ville":164      return { category: "rangee", subtype: null };165    case "Jumelé":166      return { category: "jumele", subtype: houseSubtype() };167    case "Chalet":168      return { category: "chalet", subtype: null };169    case "Maison mobile":170      return { category: "mobile", subtype: null };171    case "Fermette/Agricole":172      return { category: "fermette", subtype: null };173    case "Maison":174    case "Détachée":175      if (/\bjumele\b/.test(h)) return { category: "jumele", subtype: houseSubtype() };176      if (/en rangee|maison de ville/.test(h)) return { category: "rangee", subtype: houseSubtype() };177      return { category: "unifamiliale", subtype: houseSubtype() };178    case "Propriétés résidentielles":179    case "Résidentiel":180      if (/condo|copropriete|appartement|loft/.test(h)) return { category: "condo", subtype: null };181      if (/duplex/.test(h)) return { category: "plex", subtype: "Duplex" };182      if (/triplex/.test(h)) return { category: "plex", subtype: "Triplex" };183      if (/quadruplex|quintuplex|multiplex/.test(h)) return { category: "plex", subtype: "Multiplex" };184      if (/\bjumele\b/.test(h)) return { category: "jumele", subtype: houseSubtype() };185      if (/en rangee|maison de ville/.test(h)) return { category: "rangee", subtype: houseSubtype() };186      if (/maison mobile/.test(h)) return { category: "mobile", subtype: null };187      if (/chalet/.test(h)) return { category: "chalet", subtype: null };188      if (/plain pied|bungalow|etages|cottage|paliers|maison|detache/.test(h)) {189        return { category: "unifamiliale", subtype: houseSubtype() };190      }191      return null;192    default:193      return null;194  }195}196197function cleanCity(city: string): string {198  return city199    .replace(/^city of\s+/i, "")200    .replace(/\s*\/.*$/, "")201    .replace(/\s*\(.*\)\s*$/, "")202    .replace(/\s+/g, " ")203    .trim();204}205206const AMOUNT =207  /(?:(?:\$|\bCAD|\bCA\$)\s?\d[\d\s\u00a0\u202f.,]*\d|\d[\d\s\u00a0\u202f.,]*\s?(?:\$|CAD\b|dollars?\b|mille\s+dollars\b|k\s?\$|K\b|M\s?\$|millions?\b))/gi;208/** Nombre de 6 ou 7 chiffres sans séparateur (ex. « 349900 ») qui n'est pas une superficie. */209const BARE_PLAIN = /\b\d{6,7}\b(?!\s?(?:pi|pc|p\.c|pieds|m²|m2|mètres|metres|acres|hectares|ha\b))/gi;210/** Grand nombre isolé (≥ 50 000) qui n'est pas une superficie. */211const BARE_BIG = /\b\d{2,3}(?:[\s  .,]\d{3})+\b(?!\s?(?:pi|pc|p\.c|pieds|m²|m2|mètres|metres|acres|hectares|ha\b))/gi;212213/**214 * Retire d'une description tout ce qui pourrait révéler le prix ou permettre de215 * retrouver l'annonce : montants, liens, courriels, téléphones, numéros216 * d'inscription et adresse civique.217 */218export function sanitizeDescription(text: string | null, address: string | null, maxLength = 900): string | null {219  if (!text) return null;220  let s = text221    .replace(/<[^>]+>/g, " ")222    .replace(/https?:\/\/\S+|www\.\S+/gi, " ")223    .replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, " ")224    .replace(/\(?\b\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\b/g, " ")225    .replace(/\b(?:centris|mls|ula|no\.?|#)\s*[:#°]?\s*\d{6,9}\b/gi, " ")226    .replace(/\b\d{7,9}\b/g, " ")227    .replace(/\b[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d\b/g, " ")228    .replace(AMOUNT, "[montant retiré]")229    .replace(BARE_BIG, "[montant retiré]")230    .replace(BARE_PLAIN, "[montant retiré]");231  if (address) {232    const street = address.trim();233    if (street.length >= 6) {234      const escaped = street.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "[\\s,]+");235      s = s.replace(new RegExp(escaped, "gi"), "[adresse retirée]");236    }237  }238  s = s.replace(/\s+/g, " ").trim();239  // Par prudence : s'il subsiste un symbole monétaire, on n'affiche pas la description.240  if (/\$|€/.test(s.replace(/\[montant retiré\]/g, ""))) return null;241  if (s.length < 60) return null;242  // Texte générique court, vidé de sa substance par le nettoyage : inutile au joueur.243  if (s.length < 220 && /\[(montant|adresse) retirée?\]/.test(s)) return null;244  if (s.length > maxLength) {245    const cut = s.slice(0, maxLength);246    const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));247    s = end > maxLength * 0.5 ? cut.slice(0, end + 1) : `${cut.slice(0, cut.lastIndexOf(" "))}…`;248  }249  return s;250}251252function buildAssessment(details: Details, vp: Record<string, unknown>): Assessment | null {253  let total = typeof vp.valeur_role === "number" ? vp.valeur_role : null;254  let land = typeof vp.valeur_terrain === "number" ? vp.valeur_terrain : null;255  let building = typeof vp.valeur_batiment === "number" ? vp.valeur_batiment : null;256  if (!total) {257    total = parseMoney(details["Évaluation municipale (total)"]) ?? parseMoney(details["Évaluation municipale"]);258    land = parseMoney(details["Évaluation municipale (terrain)"]);259    building = parseMoney(details["Évaluation municipale (bâtiment)"]);260    if (!total && land && building) total = land + building;261  }262  if (!total || total < 10_000) return null;263  const year =264    parseYearIn(details["Évaluation municipale (année)"]) ??265    parseYearIn(details["Année d'évaluation"]) ??266    parseYearIn(details["Évaluation municipale"]);267  return {268    total: Math.round(total),269    land: land && land > 0 ? Math.round(land) : null,270    building: building && building > 0 ? Math.round(building) : null,271    year,272  };273}274275export function normalizeListing(276  raw: RawListing,277  priceLog: readonly RawPricePoint[],278  options: NormalizeOptions,279): NormalizeResult {280  if (raw.active !== 1 || raw.published === 0) return { ok: false, reason: "inactive" };281  if (raw.dup_hidden === 1 || raw.dup_of) return { ok: false, reason: "duplicate_flag" };282  if (options.excludedSources.includes(raw.source)) return { ok: false, reason: "excluded_source" };283284  const details = parseJson<Details>(raw.details, {});285  if (typeof details.transaction === "string" && details.transaction !== "vente") {286    return { ok: false, reason: "not_for_sale" };287  }288  const resolved = resolveCategory(raw, details);289  if (!resolved) return { ok: false, reason: "unknown_type", detail: raw.property_type ?? "" };290291  const price = raw.price;292  if (!price || !Number.isFinite(price)) return { ok: false, reason: "price_missing" };293  if (price < options.minPrice || price > options.maxPrice) return { ok: false, reason: "price_out_of_range" };294  if ((raw.quality_score ?? 0) < options.minQualityScore) return { ok: false, reason: "low_quality" };295296  const currentYear = options.now.getUTCFullYear();297  if (raw.year_built && raw.year_built > currentYear + 3) return { ok: false, reason: "implausible_data", detail: "année" };298  if ((raw.bedrooms ?? 0) > 20 || (raw.bathrooms ?? 0) > 15) {299    return { ok: false, reason: "implausible_data", detail: "pièces" };300  }301302  let livingAreaSqft = raw.area_sqft && raw.area_sqft >= 250 && raw.area_sqft <= 25_000 ? Math.round(raw.area_sqft) : null;303  if (livingAreaSqft) {304    const perSqft = price / livingAreaSqft;305    if (perSqft < 25 || perSqft > 3_000) return { ok: false, reason: "price_incoherent", detail: "prix au pi²" };306    // Superficie douteuse (souvent celle du terrain saisie à la place) : on ne l'affiche pas plutôt que d'induire en erreur.307    if (perSqft < 55) livingAreaSqft = null;308  }309  const lotAreaSqft = raw.lot_sqft && raw.lot_sqft >= 300 && raw.lot_sqft <= 500_000_000 ? Math.round(raw.lot_sqft) : null;310  const yearBuilt = raw.year_built && raw.year_built >= 1700 ? raw.year_built : null;311312  const vp = parseJson<Record<string, unknown>>(raw.assessment_json, {});313  const vpId = typeof vp.id === "string" ? vp.id : null;314  const muniFromCode = municipalityByCode(vpId && /^\d{5}/.test(vpId) ? vpId.slice(0, 5) : null);315  const sourceCity = raw.city ? cleanCity(raw.city) : "";316  const muniFromName = municipalityByName(sourceCity);317  const muni = muniFromCode ?? muniFromName;318  const municipality = muni?.name ?? sourceCity;319  if (!municipality) return { ok: false, reason: "no_municipality" };320321  let sector = raw.sector ? raw.sector.replace(/\s+/g, " ").trim() : "";322  // La « ville » de la source est parfois un arrondissement ou un quartier.323  if (muni && sourceCity && normalizeName(sourceCity) !== normalizeName(muni.name) && !sector) sector = sourceCity;324  if (sector && (normalizeName(municipality).includes(normalizeName(sector)) || /^(autres?|n\/a)$/i.test(sector))) sector = "";325326  const regionCode = muni?.regionCode ?? regionCodeFromLabel(raw.region) ?? regionCodeFromLabel(String(details.region ?? ""));327328  const assessment = buildAssessment(details, vp);329  // Un prix sans commune mesure avec l'évaluation municipale signale une erreur de saisie.330  if (assessment && (price < assessment.total * 0.25 || price > assessment.total * 12)) {331    return { ok: false, reason: "price_incoherent", detail: "écart à l'évaluation municipale" };332  }333334  const images = parseJson<unknown[]>(raw.images, [])335    .filter((u): u is string => typeof u === "string" && /^https?:\/\//.test(u))336    .filter((u, i, all) => all.indexOf(u) === i);337338  const history: PricePoint[] = [];339  for (const point of [...priceLog].sort((a, b) => a.ts - b.ts)) {340    const date = toIsoDay(point.ts);341    if (!date || !point.price || point.price <= 0) continue;342    const last = history[history.length - 1];343    if (last && last.price === point.price) continue;344    history.push({ date, price: Math.round(point.price) });345  }346  const lastHistory = history[history.length - 1];347  const priceObservedAt =348    (lastHistory && lastHistory.price === Math.round(price) ? lastHistory.date : null) ??349    toIsoDay(raw.updated_at) ??350    toIsoDay(raw.last_seen) ??351    options.now.toISOString().slice(0, 10);352353  const garageRaw = pickField(details, ["Garage"], /attach|détach|intégr|simple|double|chauff|oui|^\d$|tempo|^non$|^aucun$/i);354  const poolRaw = pickField(details, ["Piscine"], /creus|hors|chauff|oui|intérieur|semi|^non$|^aucune?$/i);355  const garage = garageRaw && !NEGATIVE.test(garageRaw) ? (/^\d$/.test(garageRaw) ? `${garageRaw} place${garageRaw === "1" ? "" : "s"}` : garageRaw) : null;356  const pool = poolRaw && !NEGATIVE.test(poolRaw) ? poolRaw : null;357358  const mls = raw.mls ? raw.mls.replace(/\D/g, "") : "";359  const dedupeKeys: string[] = [];360  if (mls.length >= 7) dedupeKeys.push(`mls:${mls}`);361  if (raw.address && /\d/.test(raw.address)) {362    dedupeKeys.push(`adr:${normalizeName(raw.address)}|${normalizeName(municipality)}`);363  }364  if (raw.lat && raw.lng) {365    dedupeKeys.push(`geo:${raw.lat.toFixed(4)},${raw.lng.toFixed(4)}|${raw.bedrooms ?? "?"}|${Math.round(price)}`);366  }367368  const condoFees = parseMoney(details["Frais de copropriété"]);369  const revenue = parseMoney(details["Revenus annuels"]);370  const taxes = parseMoney(details["Taxes municipales"]);371  const floors = resolved.category === "condo" ? null : parseIntLoose(details["Nombre d'étages"]);372  const rooms = parseIntLoose(details["Nb de pièces"] ?? details["Nombre de pièces"]);373374  const property: NormalizedProperty = {375    sourceUid: raw.uid,376    source: raw.source,377    category: resolved.category,378    subtype: resolved.subtype,379    municipality,380    municipalityCode: muni?.code ?? null,381    sector: sector || null,382    regionCode: regionCode ?? null,383    regionName: regionName(regionCode),384    mrc: muni?.mrc || null,385    price: Math.round(price),386    priceObservedAt,387    firstSeenAt: toIsoDay(raw.first_seen),388    priceHistory: history,389    bedrooms: raw.bedrooms && raw.bedrooms > 0 ? raw.bedrooms : null,390    bathrooms: raw.bathrooms && raw.bathrooms > 0 ? raw.bathrooms : null,391    powderRooms: raw.powder_rooms && raw.powder_rooms > 0 ? raw.powder_rooms : null,392    livingAreaSqft,393    lotAreaSqft: resolved.category === "condo" ? null : lotAreaSqft,394    yearBuilt,395    rooms: rooms && rooms > 0 && rooms < 60 ? rooms : null,396    floors: floors && floors > 0 && floors <= 5 ? floors : null,397    unitFloor: resolved.category === "condo" ? pickField(details, ["Situé à quel étage?"], /^\d{1,2}$|rez|jardin|sous-sol/i) : null,398    garage,399    pool,400    basement: pickField(details, ["Sous-sol"], /pieds|aménag|aucun|vide sanitaire|dalle|entrée|fini/i),401    heating: pickField(details, ["Mode de chauffage"], /plinthe|air|radiant|eau chaude|thermopompe|convect|bi-?énergie|poêle|foyer|géotherm|fournaise/i),402    heatingEnergy: pickField(details, ["Énergie pour le chauffage"], /électri|gaz|bois|mazout|propane|granule|solaire|géotherm/i),403    siding: pickField(details, ["Revêtement", "Revêtements"], /brique|vinyle|alumin|bois|pierre|stuc|canexel|fibro|béton|déclin|acrylique|agrégat|métal|cèdre/i),404    roofing: pickField(details, ["Revêtement de la toiture", "Toiture"], /bardeau|tôle|membrane|élastom|asphalte|gravier|métal|ardoise|cèdre/i),405    foundation: pickField(details, ["Fondation"], /béton|pierre|bloc|pilotis|dalle|pieux/i),406    windows: pickField(details, ["Fenestration", "Fenêtres", "Type de fenêtre"], /pvc|bois|alumin|hybride/i),407    parking: pickField(details, ["Stationnement (total)", "Stationnement"], /allée|garage|abri|extérieur|\(\d+\)/i),408    view: pickField(details, ["Vue"], /eau|montagne|panoram|ville|lac|fleuve|rivière|forêt|golf/i),409    waterfront: pickField(details, ["Eau (accès)", "Bord de l'eau"], /lac|rivi|fleuve|accès|bordé|navigable|baie|ruisseau/i),410    siteFeatures: pickField(details, ["Particularités du site"], /voisin|coin|cul-de-sac|villégiature|boisé|privé/i),411    fireplace: pickField(details, ["Foyers-poêles"], /foyer|poêle/i),412    condoFeesYearly: resolved.category === "condo" && condoFees && condoFees >= 300 && condoFees <= 60_000 ? condoFees : null,413    annualRevenue: resolved.category === "plex" && revenue && revenue >= 3_000 ? revenue : null,414    municipalTaxes: taxes && taxes >= 100 && taxes <= 200_000 ? taxes : null,415    assessment,416    description: sanitizeDescription(raw.description, raw.address),417    imageUrls: images,418    lat: raw.lat && raw.lng && raw.lat > 44 && raw.lat < 63 && raw.lng < -56 && raw.lng > -80 ? raw.lat : null,419    lng: raw.lat && raw.lng && raw.lat > 44 && raw.lat < 63 && raw.lng < -56 && raw.lng > -80 ? raw.lng : null,420    qualityScore: raw.quality_score ?? 0,421    dedupeKeys,422  };423  return { ok: true, property };424}425426/** Nombre de caractéristiques descriptives réellement connues (mesure de complétude). */427export function completeness(p: NormalizedProperty): number {428  const fields = [p.bedrooms, p.bathrooms, p.livingAreaSqft, p.lotAreaSqft, p.yearBuilt, p.garage, p.basement, p.heating, p.siding, p.parking, p.rooms];429  return fields.filter((v) => v !== null && v !== undefined).length;430}431432export interface EligibilityRules {433  minImages: number;434  minCompleteness: number;435  requireRegion: boolean;436}437438export const OFFICIAL_ELIGIBILITY: EligibilityRules = { minImages: 5, minCompleteness: 4, requireRegion: true };439440/** Admissibilité au jeu : assez de photos et assez de données pour raisonner. */441export function isEligible(p: NormalizedProperty, rules: EligibilityRules = OFFICIAL_ELIGIBILITY): boolean {442  if (p.imageUrls.length < rules.minImages) return false;443  if (rules.requireRegion && !p.regionCode) return false;444  if (!p.bedrooms && p.category !== "plex") return false;445  if (!p.bathrooms && p.category !== "plex") return false;446  if (!p.livingAreaSqft && !p.yearBuilt && !p.lotAreaSqft) return false;447  return completeness(p) >= rules.minCompleteness;448}449450/** Élimine les doublons : deux propriétés partageant une clé ne font qu'une (on garde la mieux documentée). */451export function dedupeProperties(properties: readonly NormalizedProperty[]): NormalizedProperty[] {452  const sorted = [...properties].sort(453    (a, b) => b.qualityScore - a.qualityScore || completeness(b) - completeness(a) || a.sourceUid.localeCompare(b.sourceUid),454  );455  const seen = new Set<string>();456  const kept: NormalizedProperty[] = [];457  for (const p of sorted) {458    if (p.dedupeKeys.some((k) => seen.has(k))) continue;459    for (const k of p.dedupeKeys) seen.add(k);460    kept.push(p);461  }462  return kept;463}464
Files main
Menu

Theme