Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/connectors/apchq-ai.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 * Lecture assistée des grilles APCHQ : Claude Haiku 4.5 lit le PDF (document44 * base64) et TRANSCRIT les lignes (métier, classification, montants). L'IA ne45 * fixe aucun prix : chaque ligne est ensuite vérifiée doublement —46 * 1. cohérence interne : base + vacances + avantages + cotisations ≈ total ;47 * 2. les couples (taux horaire, total) doivent exister dans l'extraction48 * déterministe (regex) du même document.49 * Les lignes qui échouent sont rejetées. Sert à rétablir les libellés que la50 * conversion PDF → markdown décale ou fusionne.51 */52import Anthropic from "@anthropic-ai/sdk";53import type Database from "better-sqlite3";54import { getCostDb } from "../db";55import type { ApchqRow } from "./apchq";5657const MODEL = "claude-haiku-4-5";5859interface AiRow {60 trade: string;61 classification: string;62 base_wage: number;63 vacation: number | null;64 benefits: number | null;65 total: number;66 contributions_sum: number | null;67}6869const TOOL: Anthropic.Tool = {70 name: "record_rows",71 description: "Transcrit toutes les lignes de la grille de coût horaire (une ligne par métier/occupation et par classification).",72 strict: true,73 input_schema: {74 type: "object",75 additionalProperties: false,76 properties: {77 effective_date: { type: ["string", "null"], description: "Date d'entrée en vigueur (YYYY-MM-DD) lue dans l'en-tête" },78 sector: { type: ["string", "null"], description: "Secteur lu dans l'en-tête (résidentiel léger, lourd, institutionnel-commercial…)" },79 rows: {80 type: "array",81 items: {82 type: "object",83 additionalProperties: false,84 properties: {85 trade: { type: "string", description: "Libellé exact du métier ou de l'occupation (ligne compagnon), tel qu'imprimé" },86 classification: { type: "string", enum: ["compagnon", "apprenti-1", "apprenti-2", "apprenti-3", "apprenti-4", "apprenti-5"] },87 base_wage: { type: "number", description: "Taux horaire ($)" },88 vacation: { type: ["number", "null"], description: "Indemnité de vacances ($)" },89 benefits: { type: ["number", "null"], description: "Avantages sociaux ($)" },90 contributions_sum: { type: ["number", "null"], description: "Somme de toutes les autres colonnes entre avantages sociaux et Total ($)" },91 total: { type: "number", description: "Colonne Total ($)" },92 },93 required: ["trade", "classification", "base_wage", "vacation", "benefits", "contributions_sum", "total"],94 },95 },96 },97 required: ["effective_date", "sector", "rows"],98 },99};100101const SYSTEM = `Tu es un moteur de transcription de tableaux. On te fournit un PDF de l'APCHQ « Coût horaire de la main-d'œuvre » (grille par métier : taux horaire, indemnité de vacances, avantages sociaux, cotisations et prélèvements, Total).102Règles strictes : transcris UNIQUEMENT les nombres imprimés, sans arrondir ni calculer ; une ligne par métier/occupation et par classification (la ligne du métier = compagnon, puis « Apprenti-période n » = apprenti-n) ; si une valeur est illisible, mets null ; ne saute aucune ligne, y compris la section « Occupations » ; n'invente jamais une ligne. Réponds seulement par l'appel de l'outil record_rows.`;103104export interface AiExtractResult {105 rows: ApchqRow[];106 checked: number;107 dropped: number;108 usage: { input: number; output: number; cacheRead: number; latencyMs: number };109}110111export async function downloadPdf(url: string, timeoutMs = 60_000): Promise<Buffer> {112 const ctrl = new AbortController();113 const t = setTimeout(() => ctrl.abort(), timeoutMs);114 try {115 const res = await fetch(url, { signal: ctrl.signal, headers: { "User-Agent": "Vrai-Prix cost connector (contact@spboucher.ai)" } });116 if (!res.ok) throw new Error(`PDF HTTP ${res.status}`);117 return Buffer.from(await res.arrayBuffer());118 } finally {119 clearTimeout(t);120 }121}122123/** Croise la transcription IA avec les couples (base, total) trouvés par le parseur déterministe. */124export function reconcile(ai: AiRow[], regexRows: ApchqRow[], fixedOther: number): { rows: ApchqRow[]; dropped: number } {125 const pairs = new Set(regexRows.map((r) => `${r.baseWage.toFixed(2)}|${r.total.toFixed(2)}`));126 const bases = new Set(regexRows.map((r) => r.baseWage.toFixed(2)));127 const totals = new Set(regexRows.map((r) => r.total.toFixed(2)));128 const rows: ApchqRow[] = [];129 let dropped = 0;130 const seen = new Set<string>();131 for (const a of ai) {132 if (!(a.base_wage > 10 && a.base_wage < 200) || !(a.total > a.base_wage * 1.25 && a.total < a.base_wage * 2.1)) { dropped++; continue; }133 const key = `${a.base_wage.toFixed(2)}|${a.total.toFixed(2)}`;134 const inRegex = pairs.has(key) || (bases.has(a.base_wage.toFixed(2)) && totals.has(a.total.toFixed(2)));135 const vac = a.vacation != null && a.vacation >= a.base_wage * 0.1 && a.vacation <= a.base_wage * 0.16 ? a.vacation : Math.round(a.base_wage * 0.13 * 100) / 100;136 const ben = a.benefits != null && a.benefits >= 3 && a.benefits <= 14 ? a.benefits : null;137 const sumOk = a.contributions_sum != null && ben != null ? Math.abs(a.base_wage + vac + ben + a.contributions_sum - a.total) <= 0.08 : false;138 if (!inRegex && !sumOk) { dropped++; continue; }139 const k = `${a.trade.toLowerCase()}|${a.classification}`;140 if (seen.has(k)) continue;141 seen.add(k);142 const benefits = ben ?? 0;143 const employer = Math.max(0, Math.round((a.total - a.base_wage - vac - benefits - fixedOther) * 100) / 100);144 rows.push({ trade: a.trade.trim(), classification: a.classification, baseWage: a.base_wage, vacation: vac, benefits, otherFixed: fixedOther, employer, total: a.total, exactBreakdown: inRegex && sumOk });145 }146 return { rows, dropped };147}148149export async function extractApchqWithClaude(pdf: Buffer, regexRows: ApchqRow[], meta: { url: string; sector: string; effectiveDate: string }, d: Database.Database = getCostDb()): Promise<AiExtractResult> {150 const client = new Anthropic();151 const t0 = Date.now();152 const res = await client.messages.create({153 model: MODEL,154 max_tokens: 16000,155 system: SYSTEM,156 tools: [TOOL],157 tool_choice: { type: "tool", name: "record_rows" },158 messages: [{ role: "user", content: [159 { type: "document", source: { type: "base64", media_type: "application/pdf", data: pdf.toString("base64") } },160 { type: "text", text: `Grille « ${meta.sector} » en vigueur au ${meta.effectiveDate} (${meta.url}). Transcris toutes les lignes.` },161 ] }],162 });163 const latencyMs = Date.now() - t0;164 const usage = { input: res.usage.input_tokens, output: res.usage.output_tokens, cacheRead: res.usage.cache_read_input_tokens ?? 0, latencyMs };165 try {166 d.prepare("INSERT INTO ai_usage(analysis_id,purpose,model,input_images,input_tokens,output_tokens,cache_read_tokens,estimated_cost_usd,latency_ms) VALUES(NULL,'apchq_extract',?,0,?,?,?,?,?)")167 .run(MODEL, usage.input, usage.output, usage.cacheRead, (usage.input * 1 + usage.output * 5) / 1e6, latencyMs);168 } catch { /* table absente en test */ }169 const tu = res.content.find((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");170 if (!tu) return { rows: [], checked: 0, dropped: 0, usage };171 const input = tu.input as { rows?: AiRow[] };172 const ai = Array.isArray(input.rows) ? input.rows.filter((r) => r && typeof r.trade === "string" && typeof r.base_wage === "number" && typeof r.total === "number") : [];173 const fixedOther = regexRows[0]?.otherFixed ?? 1.203;174 const { rows, dropped } = reconcile(ai, regexRows, fixedOther);175 return { rows, checked: ai.length, dropped, usage };176}177