All files / src/services ruleNer.ts

0% Statements 0/178
100% Branches 1/1
100% Functions 1/1
0% Lines 0/178

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import type { ExtractionResult, Identity, Address, Property, Contract } from '../types'
 
function toTitleCase(input: string): string {
  return input
    .toLowerCase()
    .split(/\s+/)
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ')
}
 
function extractMRZ(text: string): { firstName?: string; lastName?: string } | null {
  // Cherche MRZ (deux lignes, < comme séparateur). Stricte A-Z0-9<
  const lines = text.split(/\n|\r/).map((l) => l.trim().toUpperCase())
  for (let i = 0; i < lines.length - 1; i += 1) {
    const a = lines[i].replace(/[^A-Z0-9<]/g, '')
    const b = lines[i + 1].replace(/[^A-Z0-9<]/g, '')
    if (a.includes('<<') || b.includes('<<')) {
      const target = a.length >= b.length ? a : b
      const parts = target.split('<<')
      if (parts.length >= 2) {
        const rawLast = parts[0].replace(/<+/g, ' ').trim()
        const rawFirst = parts[1].replace(/<+/g, ' ').trim()
        if (rawLast && rawFirst) return { firstName: toTitleCase(rawFirst), lastName: rawLast.replace(/\s+/g, ' ') }
      }
    }
  }
  return null
}
 
function extractDates(text: string): string[] {
  const results = new Set<string>()
  const patterns = [
    /(\b\d{2}[\/\-]\d{2}[\/\-]\d{4}\b)/g, // JJ/MM/AAAA ou JJ-MM-AAAA
    /(\b\d{4}[\/\-]\d{2}[\/\-]\d{2}\b)/g, // AAAA/MM/JJ
  ]
  for (const re of patterns) {
    for (const m of text.matchAll(re)) results.add(m[1])
  }
  return Array.from(results)
}
 
function extractCniNumbers(text: string): string[] {
  const results = new Set<string>()
  const re = /\b[A-Z0-9]{12,15}\b/g
  for (const m of text.toUpperCase().matchAll(re)) results.add(m[0])
  return Array.from(results)
}
 
function extractAddresses(text: string): Address[] {
  const items: Address[] = []
 
  // Pattern amélioré pour les adresses françaises
  const addressPatterns = [
    // "123 Rue de la Paix, 75001 Paris"
    /(\d{1,4})\s+([A-Za-zÀ-ÖØ-öø-ÿ\s\-']+?),\s*(\d{5})\s+([A-Za-zÀ-ÖØ-öø-ÿ\s\-']+)/gi,
    // "demeurant 123 Rue de la Paix, 75001 Paris"
    /demeurant\s+(\d{1,4})\s+([A-Za-zÀ-ÖØ-öø-ÿ\s\-']+?),\s*(\d{5})\s+([A-Za-zÀ-ÖØ-öø-ÿ\s\-']+)/gi,
    // "situé 123 Rue de la Paix, 75001 Paris"
    /situé\s+(\d{1,4})\s+([A-Za-zÀ-ÖØ-öø-ÿ\s\-']+?),\s*(\d{5})\s+([A-Za-zÀ-ÖØ-öø-ÿ\s\-']+)/gi
  ]
 
  for (const pattern of addressPatterns) {
    for (const match of text.matchAll(pattern)) {
      const street = `${match[1]} ${toTitleCase(match[2].trim())}`
      const postalCode = match[3]
      const city = toTitleCase(match[4].trim())
 
      items.push({
        street,
        city,
        postalCode,
        country: 'France'
      })
    }
  }
 
  return items
}
 
function extractNames(text: string): Identity[] {
  const identities: Identity[] = []
 
  // Pattern pour "Vendeur : Prénom Nom" ou "Acheteur : Prénom Nom"
  const rolePattern = /(Vendeur|Acheteur|Vendeuse|Acheteuse|Propriétaire|Locataire|Bailleur|Preneur)\s*:\s*([A-Z][a-zà-öø-ÿ'\-]+\s+[A-Z][a-zà-öø-ÿ'\-]+)/gi
 
  for (const match of text.matchAll(rolePattern)) {
    const fullName = match[2].trim()
    const nameParts = fullName.split(/\s+/)
    const firstName = nameParts[0]
    const lastName = nameParts.slice(1).join(' ')
 
    identities.push({
      id: `role-${identities.length}`,
      type: 'person',
      firstName: toTitleCase(firstName),
      lastName: toTitleCase(lastName),
      confidence: 0.9,
    })
  }
 
  // Pattern pour "né le DD/MM/YYYY" ou "née le DD/MM/YYYY"
  const birthPattern = /(né|née)\s+le\s+(\d{2}\/\d{2}\/\d{4})/gi
  for (const match of text.matchAll(birthPattern)) {
    const birthDate = match[2]
    // Associer la date de naissance à la dernière identité trouvée
    if (identities.length > 0) {
      identities[identities.length - 1].birthDate = birthDate
    }
  }
 
  // Fallback: heuristique lignes en MAJUSCULES pour NOM
  if (identities.length === 0) {
    const lines = text.split(/\n|\r/).map((l) => l.trim()).filter(Boolean)
    for (let i = 0; i < lines.length; i += 1) {
      const line = lines[i]
      if (/^[A-ZÀ-ÖØ-Þ\-\s]{3,}$/.test(line) && line.length <= 40) {
        const lastName = line.replace(/\s+/g, ' ').trim()
        const cand = (lines[i + 1] || '').trim()
        const firstNameMatch = cand.match(/^[A-Z][a-zà-öø-ÿ'\-]{1,}(?:\s+[A-Z][a-zà-öø-ÿ'\-]{1,})?$/)
        const firstName = firstNameMatch ? cand : undefined
        if (lastName && (!firstName || firstName.length <= 40)) {
          identities.push({
            id: `id-${i}`,
            type: 'person',
            firstName: firstName ? toTitleCase(firstName) : undefined,
            lastName,
            confidence: firstName ? 0.85 : 0.7,
          })
        }
      }
    }
  }
 
  return identities
}
 
export function runRuleNER(documentId: string, text: string): ExtractionResult {
  console.log('🔍 [RULE-NER] Début de l\'analyse du texte...')
  console.log('📄 [RULE-NER] Longueur du texte:', text.length)
 
  const identitiesFromMRZ = extractMRZ(text)
  console.log('🆔 [RULE-NER] MRZ détecté:', !!identitiesFromMRZ)
 
  const identities = identitiesFromMRZ
    ? [
        {
          id: 'mrz-1',
          type: 'person',
          firstName: identitiesFromMRZ.firstName,
          lastName: identitiesFromMRZ.lastName!,
          confidence: 0.9,
        } as Identity,
      ]
    : extractNames(text)
 
  console.log('👥 [RULE-NER] Identités extraites:', identities.length, identities)
 
  const addresses = extractAddresses(text)
  console.log('🏠 [RULE-NER] Adresses extraites:', addresses.length, addresses)
 
  const cniNumbers = extractCniNumbers(text)
  console.log('🆔 [RULE-NER] Numéros CNI détectés:', cniNumbers.length, cniNumbers)
 
  const dates = extractDates(text)
  console.log('📅 [RULE-NER] Dates détectées:', dates.length, dates)
 
  const contracts: Contract[] = []
  const properties: Property[] = []
 
  const reasons: string[] = []
  if (identities.length) reasons.push('Identités détectées par règles')
  if (addresses.length) reasons.push('Adresse(s) détectée(s) par motifs')
  if (cniNumbers.length) reasons.push('Numéro CNI plausible détecté')
  if (dates.length) reasons.push('Dates détectées')
 
  let documentType = 'Document'
  if (/carte\s+nationale\s+d'identité|cni|mrz|identite/i.test(text)) {
    documentType = 'CNI'
    console.log('📋 [RULE-NER] Type détecté: CNI')
  } else if (/facture|tva|siren|montant/i.test(text)) {
    documentType = 'Facture'
    console.log('📋 [RULE-NER] Type détecté: Facture')
  } else if (/attestation|certificat/i.test(text)) {
    documentType = 'Attestation'
    console.log('📋 [RULE-NER] Type détecté: Attestation')
  } else if (/contrat|vente|achat|acte/i.test(text)) {
    documentType = 'Contrat'
    console.log('📋 [RULE-NER] Type détecté: Contrat')
  } else {
    console.log('📋 [RULE-NER] Type détecté: Document (par défaut)')
  }
 
  // Confiance: base 0.6 + bonus par signal
  let confidence = 0.6
  if (identities.length) confidence += 0.15
  if (cniNumbers.length) confidence += 0.15
  if (addresses.length) confidence += 0.05
  confidence = Math.max(0, Math.min(1, confidence))
 
  console.log('📊 [RULE-NER] Confiance calculée:', confidence)
  console.log('📝 [RULE-NER] Raisons:', reasons)
 
  const result = {
    documentId,
    text,
    language: 'fr',
    documentType,
    identities,
    addresses,
    properties,
    contracts,
    signatures: [],
    confidence,
    confidenceReasons: reasons,
  }
 
  console.log('✅ [RULE-NER] Résultat final:', result)
  return result
}