Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/ai/service.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 * Service d'analyse IA des annonces (SERVEUR) : file de travaux en mémoire44 * avec états persistés (§168), idempotence par empreinte (§131-132, 169),45 * limites/budget (§183-184), pipeline complet :46 * photos → Claude Sonnet 5 → validation → fusion des sources → vecteur →47 * mapping assemblages → moteur de coût déterministe → estimation sauvegardée.48 * Recalcul aux coûts d'aujourd'hui, corrections manuelles et similaires49 * techniques ne rappellent JAMAIS le modèle.50 */51import { randomUUID } from "crypto";52import { loadAssemblies } from "../catalog";53import { getEstimate, runEstimate } from "../estimate";54import type { CostEstimate } from "../types";55import { inputHash, loadListingContext, type ListingContext } from "./context";56import { prepareListingImages, purgeImageCache, type PreparedImage } from "./images";57import { applyOverrides, mergeFacts, type Conflict, type MergedFacts } from "./merge";58import { combinedConfidence, mapToCostInput, type MappingResult } from "./mapping";59import { ClaudeSonnet5Provider, type PropertyVisionModel } from "./provider";60import { PROMPT_VERSION, SCHEMA_VERSION, type ImageManifestEntry, type ModelOutput, type PropertyTechnicalAnalysis } from "./schema";61import * as store from "./store";62import { EMBEDDING_MODEL, canonicalText, cosine, costProfileVector, technicalVector } from "./vector";63import { computeGeometry } from "../geometry";6465export const MAX_IMAGES = Number(process.env.PROPERTY_ANALYSIS_MAX_IMAGES ?? 40);66export const DAILY_MAX = Number(process.env.AI_ANALYSIS_DAILY_MAX ?? 30);67export const DAILY_BUDGET_USD = Number(process.env.AI_DAILY_BUDGET_USD ?? 15);6869export class AnalysisError extends Error {70 constructor(message: string, public status = 400, public code = "bad_request") { super(message); }71}7273/* --------------------------------------------------------------- file */7475const running = new Set<string>();76let provider: PropertyVisionModel | null = null;77export function setProvider(p: PropertyVisionModel | null): void { provider = p; }78function getProvider(): PropertyVisionModel { return provider ?? (provider = new ClaudeSonnet5Provider()); }7980export interface StartResult { analysisId: string; status: store.AnalysisStatus; reused: boolean; version: number }8182/** Démarre (ou réutilise) une analyse. `force` crée une nouvelle version même si l'empreinte est connue. */83export async function startAnalysis(uid: string, opts: { force?: boolean } = {}): Promise<StartResult> {84 const ctx = loadListingContext(uid);85 if (!ctx) throw new AnalysisError("Annonce introuvable.", 404, "not_found");86 if (!ctx.imageUrls.length) throw new AnalysisError("Cette annonce n'a aucune photo : l'analyse multimodale n'est pas possible.", 422, "no_images");87 if (!process.env.ANTHROPIC_API_KEY) throw new AnalysisError("Modèle indisponible (clé API absente côté serveur).", 503, "model_unavailable");88 store.failOrphans(); // une analyse figée par un redémarrage ne doit jamais bloquer une nouvelle demande89 const active = store.findActive(uid);90 if (active) return { analysisId: active.id, status: active.status, reused: true, version: active.version };91 // empreinte provisoire (sans hashes d'images) pour la réutilisation rapide ; l'empreinte finale inclut les hashes92 const model = getProvider().model;93 if (!opts.force) {94 // réutilisation sans retéléchargement : si toutes les photos sont déjà connues, l'empreinte finale est calculable95 const known = store.knownImageHashes(uid);96 if (ctx.imageUrls.every((u) => known.has(u))) {97 const full = inputHash(ctx.baseHashInput, ctx.imageUrls.map((u) => known.get(u)!));98 const prev = store.findCompleted(uid, full, PROMPT_VERSION, model);99 if (prev) return { analysisId: prev.id, status: "completed", reused: true, version: prev.version };100 }101 }102 if (store.analysesStartedToday() >= DAILY_MAX) throw new AnalysisError(`Quota quotidien d'analyses atteint (${DAILY_MAX}).`, 429, "daily_quota");103 const u = store.usageToday();104 if (u.costUsd >= DAILY_BUDGET_USD) throw new AnalysisError("Budget quotidien d'analyse IA épuisé — réessayez demain.", 429, "budget");105 const id = randomUUID();106 const row = store.createAnalysis({ id, listingUid: uid, model, promptVersion: PROMPT_VERSION, schemaVersion: SCHEMA_VERSION, inputHash: `${quickHash(ctx)}:pending`, listingJson: JSON.stringify(ctx.analysisListing) });107 void runPipeline(id, ctx, opts.force ?? false);108 return { analysisId: id, status: row.status, reused: false, version: row.version };109}110111function quickHash(ctx: ListingContext): string { return inputHash(ctx.baseHashInput, []).slice(0, 24); }112113async function runPipeline(id: string, ctx: ListingContext, force: boolean): Promise<void> {114 if (running.has(id)) return;115 running.add(id);116 try {117 store.setStage(id, "fetching_images");118 const imgs = await prepareListingImages(ctx.uid, ctx.imageUrls, MAX_IMAGES);119 if (!imgs.selected.length) throw new Error(`Aucune photo exploitable (${imgs.failed.length} échec(s) : ${imgs.failed.slice(0, 3).map((f) => f.error).join(" ; ")})`);120 // empreinte finale : toutes les photos téléchargées (y compris doublons/miniatures écartés)121 const fetchedHashes = new Map(imgs.all.map((i) => [i.sourceUrl, i.hash]));122 const known = store.knownImageHashes(ctx.uid);123 const hash = inputHash(ctx.baseHashInput, ctx.imageUrls.map((u) => fetchedHashes.get(u) ?? known.get(u) ?? `missing:${u}`));124 store.db().prepare("UPDATE listing_ai_analyses SET input_hash=? WHERE id=?").run(hash, id);125 store.saveImages(ctx.uid, id, imgs.all.map((i) => ({ ...i, selected: !!i.id })));126 if (!force) {127 const prev = store.findCompleted(ctx.uid, hash, PROMPT_VERSION, getProvider().model);128 if (prev && prev.id !== id) {129 // même entrée déjà analysée : on réutilise la sortie du modèle sans rappeler Claude130 finishFromPrevious(id, prev, ctx, imgs.selected);131 return;132 }133 }134 store.setStage(id, "analyzing");135 const assemblies = loadAssemblies();136 const codes = [...assemblies.keys()];137 const catalogue = [...assemblies.values()].map((a) => `${a.code} | ${a.nameEn} (${a.nameFr}) | unit: ${a.unit}`).join("\n");138 const res = await getProvider().analyze({ listingContext: ctx.text, images: imgs.selected.map((i) => ({ id: i.id, mediaType: i.mediaType, data: i.data, roomHint: i.roomHint, position: i.position })), assemblyCodes: codes, assemblyCatalogueText: catalogue });139 store.recordUsage({ analysisId: id, purpose: "property_analysis", model: res.model, images: imgs.selected.length, inputTokens: res.usage.inputTokens, outputTokens: res.usage.outputTokens, cacheRead: res.usage.cacheReadTokens, costUsd: res.usage.estimatedCostUsd, latencyMs: res.usage.latencyMs });140 store.setStage(id, "validating");141 const manifest: ImageManifestEntry[] = imgs.selected.map((i) => ({ id: i.id, position: i.position, room_hint: i.roomHint, source_url: i.sourceUrl, hash: i.hash, width: i.width, height: i.height }));142 store.saveOutput(id, { outputJson: JSON.stringify(res.output), imageCount: imgs.selected.length, usageJson: JSON.stringify({ ...res.usage, model: res.model, duplicatesRemoved: imgs.duplicatesRemoved, thumbnailsRemoved: imgs.thumbnailsRemoved, failed: imgs.failed }), issuesJson: JSON.stringify(res.issues), imagesJson: JSON.stringify(manifest) });143 completeFromOutput(id, ctx, res.output, manifest);144 } catch (e) {145 store.setFailed(id, (e as Error).message);146 } finally {147 running.delete(id);148 try { purgeImageCache(); } catch { /* ignore */ }149 }150}151152function finishFromPrevious(id: string, prev: store.AnalysisRow, ctx: ListingContext, selected: PreparedImage[]): void {153 const output = JSON.parse(prev.output_json ?? "null") as ModelOutput | null;154 if (!output) { store.setFailed(id, "analyse précédente sans sortie"); return; }155 const manifest = (JSON.parse(prev.images_json ?? "[]") as ImageManifestEntry[]).length ? (JSON.parse(prev.images_json!) as ImageManifestEntry[]) : selected.map((i) => ({ id: i.id, position: i.position, room_hint: i.roomHint, source_url: i.sourceUrl, hash: i.hash, width: i.width, height: i.height }));156 store.saveOutput(id, { outputJson: JSON.stringify(output), imageCount: manifest.length, usageJson: JSON.stringify({ reusedFrom: prev.id, estimatedCostUsd: 0 }), issuesJson: "[]", imagesJson: JSON.stringify(manifest) });157 completeFromOutput(id, ctx, output, manifest);158}159160/** Étapes déterministes après la sortie du modèle : fusion → vecteur → mapping → coût. */161function completeFromOutput(id: string, ctx: ListingContext, output: ModelOutput, manifest: ImageManifestEntry[]): void {162 store.setStage(id, "embedding");163 const merged = mergeFacts(output, ctx.facts, ctx.mamh);164 store.saveConflicts(id, merged.conflicts);165 const vec = technicalVector(merged);166 const text = canonicalText(merged);167 store.saveMergedAndVector(id, JSON.stringify(merged), JSON.stringify(vec));168 store.saveEmbedding(ctx.uid, id, EMBEDDING_MODEL, vec, text);169 store.setStage(id, "mapping_assemblies");170 priceAnalysis(id, ctx, output, merged, manifest, true);171}172173function priceAnalysis(id: string, ctx: ListingContext, output: ModelOutput, mergedBase: MergedFacts, manifest: ImageManifestEntry[], completed: boolean): CostEstimate {174 const overrides = store.listOverrides(id).map((o) => ({ fieldPath: o.fieldPath, value: o.value }));175 const merged = overrides.length ? applyOverrides(mergedBase, overrides) : mergedBase;176 store.saveMergedEffective(id, JSON.stringify(merged));177 const assemblies = loadAssemblies();178 const l = ctx.detail.listing;179 const mapping = mapToCostInput(merged, output, { listingUid: ctx.uid, address: l.address, municipality: l.city, lat: l.lat, lng: l.lng, unitId: ctx.mamh?.unitId ?? null, landValue: ctx.mamh?.landValue ?? null, roll: ctx.roll, assemblyCodes: new Set(assemblies.keys()) });180 store.setStage(id, "pricing");181 const e = ctx.detail.eval;182 const est = runEstimate(mapping.input, { otherReadings: { hedonic: e?.model_est ?? null, comparables: e?.comps_est ?? null, hybrid: e?.est ?? null, askingPrice: l.price, rollValue: ctx.mamh?.totalValue ?? e?.valeur_role ?? null, rollBuilding: ctx.mamh?.buildingValue ?? null, rollLand: ctx.mamh?.landValue ?? null } });183 const mappedShare = output.assemblies.length ? output.assemblies.filter((a) => assemblies.has(a.assembly_code)).length / output.assemblies.length : 0.8;184 const combined = combinedConfidence(output, merged, est, mappedShare);185 const compact = { building_type: mapping.input.building.type, location: est.location.code, gross_floor_area_sqft: mapping.input.building.grossFloorAreaSqft, quality: mapping.input.building.quality, assemblies: est.lines.map((li) => ({ code: li.assemblyCode, qty: li.quantity, unit: li.unit, source: li.quantitySource })), cost_profile: costProfileVector(est.categories) };186 store.saveMappingAndEstimate(id, { mappingJson: JSON.stringify({ aiQuantities: mapping.aiQuantities, notes: mapping.notes, overrides, attributeSources: mapping.input.attributeSources }), compactJson: JSON.stringify(compact), estimateId: est.id, snapshotDate: est.priceDate, combinedJson: JSON.stringify(combined), confidence: combined.overall, completed });187 void manifest;188 return est;189}190191/* ------------------------------------------------------------ lecture */192193export interface AnalysisView {194 id: string; listingUid: string; version: number; status: store.AnalysisStatus; stage: string | null; error: string | null; model: string; promptVersion: string; schemaVersion: string; createdAt: string; completedAt: string | null; imageCount: number;195 analysis: PropertyTechnicalAnalysis | null; merged: MergedFacts | null; mapping: { aiQuantities: MappingResult["aiQuantities"]; notes: string[]; overrides: { fieldPath: string; value: unknown }[]; attributeSources: Record<string, string> } | null;196 estimate: CostEstimate | null; costSnapshotDate: string | null; combined: ReturnType<typeof combinedConfidence> | null; conflicts: (Conflict & { id: number; status: string })[]; overrides: ReturnType<typeof store.listOverrides>;197 usage: Record<string, unknown> | null; versions: ReturnType<typeof store.listVersions>; compact: unknown;198}199200export function viewAnalysis(row: store.AnalysisRow): AnalysisView {201 const output = row.output_json ? (JSON.parse(row.output_json) as ModelOutput) : null;202 const merged = row.merged_json ? (JSON.parse(row.merged_json) as MergedFacts) : null;203 const listing = row.listing_json ? (JSON.parse(row.listing_json) as PropertyTechnicalAnalysis["listing"]) : null;204 const images = row.images_json ? (JSON.parse(row.images_json) as ImageManifestEntry[]) : [];205 const usage = row.usage_json ? (JSON.parse(row.usage_json) as Record<string, unknown>) : null;206 const estimate = row.estimate_id ? getEstimate(row.estimate_id) : null;207 let analysis: PropertyTechnicalAnalysis | null = null;208 if (output && listing) {209 const g = estimate ? computeGeometry(estimate.input.building) : null;210 analysis = {211 ...output,212 metadata: { analysis_id: row.id, listing_id: row.listing_uid, listing_source: row.listing_uid.split(":")[0], model: row.model, prompt_version: row.prompt_version, schema_version: row.schema_version, analysis_timestamp: row.completed_at ?? row.created_at, image_count: row.image_count, input_hash: row.input_hash, input_token_estimate: (usage?.inputTokens as number | undefined) ?? null, output_tokens: (usage?.outputTokens as number | undefined) ?? null, latency_ms: (usage?.latencyMs as number | undefined) ?? null },213 listing, images,214 derived_geometry: g ? { footprint_sqft: g.footprintSqft, perimeter_ft: g.perimeterFt, exposed_perimeter_ft: g.exposedPerimeterFt, gross_wall_sqft: g.grossWallSqft, net_wall_sqft: g.netWallSqft, roof_sqft: g.roofSqft, window_count: g.windowCount, basement_floor_sqft: g.basementFloorSqft, basement_finished_sqft: g.basementFinishedSqft, garage_sqft: g.garageSqft, formulas: Object.fromEntries(estimate!.quantities.map((q) => [q.assemblyCode, q.formula])) } : { footprint_sqft: 0, perimeter_ft: 0, exposed_perimeter_ft: 0, gross_wall_sqft: 0, net_wall_sqft: 0, roof_sqft: 0, window_count: 0, basement_floor_sqft: 0, basement_finished_sqft: 0, garage_sqft: 0, formulas: {} },215 };216 }217 return {218 id: row.id, listingUid: row.listing_uid, version: row.version, status: row.status, stage: row.stage, error: row.error, model: row.model, promptVersion: row.prompt_version, schemaVersion: row.schema_version, createdAt: row.created_at, completedAt: row.completed_at, imageCount: row.image_count,219 analysis, merged, mapping: row.mapping_json ? (JSON.parse(row.mapping_json) as AnalysisView["mapping"]) : null, estimate, costSnapshotDate: row.cost_snapshot_date, combined: row.combined_json ? (JSON.parse(row.combined_json) as AnalysisView["combined"]) : null,220 conflicts: store.listConflicts(row.id), overrides: store.listOverrides(row.id), usage, versions: store.listVersions(row.listing_uid), compact: row.compact_json ? JSON.parse(row.compact_json) : null,221 };222}223224export function getLatest(uid: string): AnalysisView | null {225 store.failOrphans();226 const row = store.latestForListing(uid);227 return row ? viewAnalysis(row) : null;228}229export function getById(id: string): AnalysisView | null {230 store.failOrphans();231 const row = store.getAnalysis(id);232 return row ? viewAnalysis(row) : null;233}234235/** Résumé pour la fiche et les cartes (analyse complète la plus récente). */236export function summaryForListing(uid: string): { analysisId: string; version: number; confidence: number | null; rcn: number | null; costValue: number | null; structure: string | null; foundation: string | null; roof: string | null; quality: string | null; condition: string | null; completedAt: string | null } | null {237 const row = store.latestCompletedForListing(uid);238 if (!row) return null;239 const merged = row.merged_json ? (JSON.parse(row.merged_json) as MergedFacts) : null;240 const est = row.estimate_id ? getEstimate(row.estimate_id) : null;241 const conds = merged ? Object.values(merged.conditions) : [];242 const cond: string | null = conds.length ? (conds.filter((c): c is NonNullable<typeof c> => !!c).sort()[Math.floor(conds.length / 2)] ?? null) : null;243 return { analysisId: row.id, version: row.version, confidence: row.confidence, rcn: est?.replacementCostNew ?? null, costValue: est?.costApproachValue ?? null, structure: merged?.structure.value ?? null, foundation: merged?.foundation.value ?? null, roof: merged?.roof.value ?? null, quality: merged?.quality.value ?? null, condition: cond, completedAt: row.completed_at };244}245246/* ------------------------------------------------- recalcul / overrides */247248/** Recalcule le coût avec les prix d'aujourd'hui (sans rappeler le modèle). */249export function recalc(analysisId: string): AnalysisView {250 const row = store.getAnalysis(analysisId);251 if (!row) throw new AnalysisError("Analyse introuvable.", 404, "not_found");252 if (row.status !== "completed" || !row.output_json || !row.merged_json) throw new AnalysisError("L'analyse n'est pas terminée.", 409, "not_completed");253 const ctx = loadListingContext(row.listing_uid);254 if (!ctx) throw new AnalysisError("Annonce introuvable.", 404, "not_found");255 const output = JSON.parse(row.output_json) as ModelOutput;256 const mergedBase = mergeFacts(output, ctx.facts, ctx.mamh); // refusionne (le rôle peut avoir changé) ; overrides réappliqués dans priceAnalysis257 store.saveMergedBase(analysisId, JSON.stringify(mergedBase));258 priceAnalysis(analysisId, ctx, output, mergedBase, JSON.parse(row.images_json ?? "[]") as ImageManifestEntry[], true);259 return viewAnalysis(store.getAnalysis(analysisId)!);260}261262const OVERRIDABLE = new Set(["buildingType", "yearBuilt", "stories", "grossFloorAreaSqft", "footprintSqft", "foundation", "structure", "siding", "roof", "roofGeometry", "roofPitch", "windows", "windowCount", "heating", "hasAirConditioning", "hasAirExchanger", "basement", "basementFinishedPct", "garage", "kitchens", "kitchenQuality", "bathrooms", "powderRooms", "bathroomQuality", "bedrooms", "quality", "flooring", "deckSqft", "drivewaySqft", "driveway", "fenceLinFt", "pool", "units", "kitchenLinearFt", "countertopSqft", "backsplashSqft", "bathroomTileSqft", "interiorDoorCount", "conditions", "effectiveAge"]);263264/** Correction manuelle d'une inférence (§140-142) : conservée, tracée, puis recalcul déterministe. */265export function override(analysisId: string, fieldPath: string, value: unknown, userId: string | null): AnalysisView {266 const row = store.getAnalysis(analysisId);267 if (!row || !row.merged_json || !row.output_json) throw new AnalysisError("Analyse introuvable ou incomplète.", 404, "not_found");268 const root = fieldPath.split(".")[0];269 if (!OVERRIDABLE.has(root)) throw new AnalysisError(`Champ non modifiable : ${fieldPath}`, 400, "bad_field");270 // base = faits avant corrections (les corrections persistées sont réappliquées dans priceAnalysis)271 const merged = JSON.parse(row.merged_base_json ?? row.merged_json) as MergedFacts;272 const effective = JSON.parse(row.merged_json) as MergedFacts;273 const cur = (merged as unknown as Record<string, { value?: unknown } | undefined>)[root];274 const curEff = (effective as unknown as Record<string, { value?: unknown } | undefined>)[root];275 void cur;276 store.addOverride(analysisId, fieldPath, root === "conditions" ? effective.conditions[fieldPath.split(".")[1]] ?? null : root === "effectiveAge" ? effective.effectiveAge?.effective ?? null : curEff?.value ?? null, value, userId);277 const ctx = loadListingContext(row.listing_uid);278 if (!ctx) throw new AnalysisError("Annonce introuvable.", 404, "not_found");279 priceAnalysis(analysisId, ctx, JSON.parse(row.output_json) as ModelOutput, merged, JSON.parse(row.images_json ?? "[]") as ImageManifestEntry[], true);280 return viewAnalysis(store.getAnalysis(analysisId)!);281}282283/* ------------------------------------------------------------ similaires */284285export function technicalSimilar(analysisId: string, limit = 6): { listingUid: string; analysisId: string; similarity: number; text: string | null }[] {286 const row = store.getAnalysis(analysisId);287 if (!row?.vector_json || !row.merged_json) return [];288 const v = JSON.parse(row.vector_json) as number[];289 const m = JSON.parse(row.merged_json) as MergedFacts;290 const all = store.allEmbeddings(EMBEDDING_MODEL).filter((e) => e.listingUid !== row.listing_uid);291 const out: { listingUid: string; analysisId: string; similarity: number; text: string | null }[] = [];292 for (const e of all) {293 const om = store.getAnalysis(e.analysisId)?.merged_json;294 if (om) {295 const mm = JSON.parse(om) as MergedFacts;296 if (mm.buildingType.value !== m.buildingType.value) continue;297 if (Math.abs(mm.grossFloorAreaSqft.value - m.grossFloorAreaSqft.value) / m.grossFloorAreaSqft.value > 0.15) continue;298 }299 out.push({ listingUid: e.listingUid, analysisId: e.analysisId, similarity: Math.round(cosine(v, e.vector) * 1000) / 1000, text: e.text });300 }301 return out.sort((a, b) => b.similarity - a.similarity).slice(0, limit);302}303