SPB Git

Repository Public

context.ts 7.2 KB 119 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/cost/ai/context.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-09-0812 * Last Modified    : 2026-09-0813 *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 * =============================================================================40 */4142/**43 * Contexte d'analyse d'une annonce : faits de l'annonce + rôle MAMH jumelé,44 * texte déterministe transmis au modèle, empreinte d'entrée (§132, 169).45 * Module PUR sauf `loadListingContext` (lecture des bases).46 */47import { createHash } from "crypto";48import { getUnit } from "../../db";49import { getListing, type ListingDetail } from "../../immoka";50import { sqftFromM2 } from "../units";51import type { BuildingType, CostInput } from "../types";52import { listingFactsFromDetails, type ListingFacts, type MamhFacts } from "./merge";53import type { AnalysisListing } from "./schema";5455export interface ListingContext {56  uid: string;57  detail: ListingDetail;58  facts: ListingFacts;59  mamh: MamhFacts | null;60  roll: CostInput["roll"];61  analysisListing: AnalysisListing;62  imageUrls: string[];63  text: string; // contexte textuel déterministe pour le modèle64  baseHashInput: string; // partie textuelle de l'empreinte (les hashes d'images s'ajoutent)65}6667function mamhType(u: { type_prop: string; lien_physique: string | null; nb_logements: number | null; aire_etages_m2: number | null }): BuildingType | null {68  switch (u.type_prop) {69    case "plex": return "plex";70    case "chalet": return "chalet";71    case "maison_mobile": return "mobile";72    case "condo_ou_multi": return (u.nb_logements ?? 1) > 1 && (u.aire_etages_m2 ?? 0) > 400 ? "plex" : "condo";73    case "unifamilial": { const l = (u.lien_physique ?? "").toLowerCase(); return l.includes("jumel") ? "semi_detached" : l.includes("rang") || l.includes("intégré") || l.includes("integre") ? "row" : "detached"; }74    default: return null;75  }76}7778export function loadListingContext(uid: string): ListingContext | null {79  const detail = getListing(uid);80  if (!detail) return null;81  const l = detail.listing;82  const facts = listingFactsFromDetails(l, detail.details);83  let mamh: MamhFacts | null = null;84  let roll: CostInput["roll"] = null;85  if (detail.eval?.unit_id) {86    const u = getUnit(detail.eval.unit_id);87    if (u) {88      const g = (u.genre_construction ?? "").toLowerCase();89      const stories = u.nb_etages && u.nb_etages > 0 ? Math.max(1, Math.round(u.nb_etages)) : g ? (g.includes("plain-pied") || g.includes("unimodulaire") ? 1 : g.includes("étages entiers") ? 2 : g.includes("mansard") || g.includes("décal") ? 2 : 1) : null;90      mamh = { yearBuilt: u.annee_construction && u.annee_construction > 1600 ? u.annee_construction : null, grossFloorAreaSqft: u.aire_etages_m2 && u.aire_etages_m2 > 15 ? Math.round(sqftFromM2(u.aire_etages_m2)) : null, stories, buildingType: mamhType(u), units: u.nb_logements, landValue: u.valeur_terrain, buildingValue: u.valeur_batiment, totalValue: u.valeur_role, unitId: u.id_provinc };91      roll = { landValue: u.valeur_terrain, buildingValue: u.valeur_batiment, totalValue: u.valeur_role, year: 2026 };92    }93  }94  const desc = (l.description ?? "").replace(/\s+/g, " ").trim();95  const detailsTxt = Object.entries(detail.details).filter(([k]) => !["img_audited", "transaction"].includes(k)).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : String(v)}`).join("\n");96  const features = detail.features.join("; ");97  const text = [98    "### Structured listing fields (source: listing)",99    `address: ${l.address ?? "—"} | municipality: ${l.city ?? "—"} | sector: ${l.sector ?? "—"} | region: ${l.region ?? "—"}`,100    `property_type: ${l.property_type ?? "—"} | asking_price_cad: ${l.price} | year_built: ${l.year_built ?? "unknown"} | living_area_sqft: ${l.area_sqft ?? "unknown"} | lot_area_sqft: ${l.lot_sqft ?? "unknown"}`,101    `bedrooms: ${l.bedrooms ?? "unknown"} | bathrooms: ${l.bathrooms ?? "unknown"} | powder_rooms: ${l.powder_rooms ?? "unknown"}`,102    detailsTxt ? `### Listing details (source: listing)\n${detailsTxt}` : "",103    features ? `### Listing features (source: listing)\n${features}` : "",104    desc ? `### Broker description (source: description)\n${desc.slice(0, 6000)}` : "",105    mamh ? `### Assessment roll — MAMH (source: MAMH, authoritative)\nyear_built: ${mamh.yearBuilt ?? "unknown"} | gross_floor_area_sqft_excluding_basement: ${mamh.grossFloorAreaSqft ?? "unknown"} | stories: ${mamh.stories ?? "unknown"} | building_type: ${mamh.buildingType ?? "unknown"} | dwelling_units: ${mamh.units ?? "unknown"} | land_value_cad: ${mamh.landValue ?? "unknown"} | building_value_cad: ${mamh.buildingValue ?? "unknown"}` : "### Assessment roll — MAMH\nnot matched",106  ].filter(Boolean).join("\n\n");107  const analysisListing: AnalysisListing = {108    address: l.address, municipality: l.city, region: l.region, asking_price: l.price, listing_date: l.first_seen ? new Date(l.first_seen * 1000).toISOString().slice(0, 10) : null, description_excerpt: desc ? desc.slice(0, 600) : null,109    bedrooms: l.bedrooms, bathrooms: l.bathrooms, powder_rooms: l.powder_rooms, lot_area_sqft: l.lot_sqft, living_area_sqft: l.area_sqft, year_built: l.year_built, property_type: l.property_type, url: l.url, unit_id: mamh?.unitId ?? null,110  };111  const baseHashInput = JSON.stringify({ urls: detail.images, description: l.description, specs: { pt: l.property_type, yb: l.year_built, a: l.area_sqft, lot: l.lot_sqft, bd: l.bedrooms, ba: l.bathrooms, pr: l.powder_rooms, details: detail.details, features: detail.features }, updated: l.updated_at, mamh });112  return { uid, detail, facts, mamh, roll, analysisListing, imageUrls: detail.images, text, baseHashInput };113}114115/** Empreinte d'entrée : URLs + hashes d'images + description + champs structurés + updated_at. */116export function inputHash(base: string, imageHashes: string[]): string {117  return createHash("sha256").update(base).update("|").update([...imageHashes].sort().join(",")).digest("hex");118}119
Files main
Menu

Theme