presidio modulaire
This commit is contained in:
1
refiners/__init__.py
Normal file
1
refiners/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Refiners package
|
||||
89
refiners/date_refiner.py
Normal file
89
refiners/date_refiner.py
Normal file
@@ -0,0 +1,89 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple
|
||||
import re
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EntityRefiner(ABC):
|
||||
"""Classe de base pour le recadrage d'entités"""
|
||||
|
||||
def __init__(self, entity_type: str):
|
||||
self.entity_type = entity_type
|
||||
|
||||
@abstractmethod
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""Recadre une entité détectée"""
|
||||
pass
|
||||
|
||||
def should_process(self, entity_type: str) -> bool:
|
||||
"""Vérifie si ce raffineur doit traiter ce type d'entité"""
|
||||
return entity_type == self.entity_type
|
||||
|
||||
class DateRefiner(EntityRefiner):
|
||||
"""Raffineur pour les dates - élimine les faux positifs"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("DATE_TIME")
|
||||
# Patterns pour valider les vraies dates
|
||||
self.valid_date_patterns = [
|
||||
# Format DD/MM/YYYY
|
||||
re.compile(r"\b(?:0[1-9]|[12][0-9]|3[01])/(?:0[1-9]|1[0-2])/(?:19|20)\d{2}\b"),
|
||||
# Format DD-MM-YYYY
|
||||
re.compile(r"\b(?:0[1-9]|[12][0-9]|3[01])-(?:0[1-9]|1[0-2])-(?:19|20)\d{2}\b"),
|
||||
# Format ISO YYYY-MM-DD
|
||||
re.compile(r"\b(?:19|20)\d{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])\b"),
|
||||
# Dates avec mois en lettres
|
||||
re.compile(r"\b(?:0?[1-9]|[12][0-9]|3[01])\s+(?:janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)\s+(?:19|20)\d{2}\b", re.IGNORECASE),
|
||||
# Heures
|
||||
re.compile(r"\b(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?\b")
|
||||
]
|
||||
|
||||
# Patterns à rejeter (faux positifs courants)
|
||||
self.reject_patterns = [
|
||||
# Codes IBAN belges (BE + chiffres)
|
||||
re.compile(r"\bBE\d{2,}\b", re.IGNORECASE),
|
||||
# Numéros d'entreprise belges
|
||||
re.compile(r"\bBE\d{3}\.\d{3}\.\d{3}\b"),
|
||||
# Mots comme HTVA, TVA, etc.
|
||||
re.compile(r"\b(?:HTVA|TVA|BCE|ONSS|SIREN|SIRET)\b", re.IGNORECASE),
|
||||
# Données sensibles (texte)
|
||||
re.compile(r"\b(?:données?\s+sensibles?)\b", re.IGNORECASE),
|
||||
# Codes postaux isolés
|
||||
re.compile(r"^\d{4}$"),
|
||||
# Codes courts (2-4 caractères alphanumériques)
|
||||
re.compile(r"^[A-Z]{2}\d{1,2}$")
|
||||
]
|
||||
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""Valide si l'entité détectée est vraiment une date"""
|
||||
ent_text = text[start:end].strip()
|
||||
|
||||
# Vérifier si c'est un pattern à rejeter
|
||||
for reject_pattern in self.reject_patterns:
|
||||
if reject_pattern.search(ent_text):
|
||||
logger.info(f"Date rejetée (faux positif): '{ent_text}'")
|
||||
return None
|
||||
|
||||
# Vérifier si c'est un pattern de date valide
|
||||
for valid_pattern in self.valid_date_patterns:
|
||||
if valid_pattern.search(ent_text):
|
||||
logger.info(f"Date validée: '{ent_text}'")
|
||||
return (start, end)
|
||||
|
||||
# Si aucun pattern valide trouvé, rejeter
|
||||
logger.info(f"Date rejetée (format invalide): '{ent_text}'")
|
||||
return None
|
||||
|
||||
def validate_date_logic(self, day: int, month: int, year: int) -> bool:
|
||||
"""Valide la logique de la date (jours/mois corrects)"""
|
||||
if month < 1 or month > 12:
|
||||
return False
|
||||
|
||||
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
||||
|
||||
# Année bissextile
|
||||
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
|
||||
days_in_month[1] = 29
|
||||
|
||||
return 1 <= day <= days_in_month[month - 1]
|
||||
49
refiners/iban_refiner.py
Normal file
49
refiners/iban_refiner.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple
|
||||
import re
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EntityRefiner(ABC):
|
||||
"""Classe de base pour le recadrage d'entités"""
|
||||
|
||||
def __init__(self, entity_type: str):
|
||||
self.entity_type = entity_type
|
||||
|
||||
@abstractmethod
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""Recadre une entité détectée"""
|
||||
pass
|
||||
|
||||
def should_process(self, entity_type: str) -> bool:
|
||||
"""Vérifie si ce raffineur doit traiter ce type d'entité"""
|
||||
return entity_type == self.entity_type
|
||||
|
||||
class IBANRefiner(EntityRefiner):
|
||||
"""Raffineur pour les IBAN"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("IBAN")
|
||||
self.iban_regex = re.compile(r"\b[A-Z]{2}[0-9]{2}(?:\s[0-9]{4}){3}\b", re.IGNORECASE)
|
||||
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
ent_text = text[start:end].strip()
|
||||
match = self.iban_regex.search(ent_text)
|
||||
|
||||
if not match:
|
||||
logger.warning(f"Invalid IBAN detected, skipping: '{ent_text}'")
|
||||
return None
|
||||
|
||||
true_iban = match.group(0)
|
||||
start_offset = ent_text.find(true_iban)
|
||||
|
||||
if start_offset == -1:
|
||||
logger.warning(f"IBAN regex match but cannot find substring position: '{ent_text}'")
|
||||
return None
|
||||
|
||||
new_start = start + start_offset
|
||||
new_end = new_start + len(true_iban)
|
||||
|
||||
logger.debug(f"Adjusted IBAN span: {start}-{end} => {new_start}-{new_end}")
|
||||
return (new_start, new_end)
|
||||
52
refiners/ip_refiner.py
Normal file
52
refiners/ip_refiner.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple
|
||||
import re
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EntityRefiner(ABC):
|
||||
"""Classe de base pour le recadrage d'entités"""
|
||||
|
||||
def __init__(self, entity_type: str):
|
||||
self.entity_type = entity_type
|
||||
|
||||
@abstractmethod
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""Recadre une entité détectée"""
|
||||
pass
|
||||
|
||||
def should_process(self, entity_type: str) -> bool:
|
||||
"""Vérifie si ce raffineur doit traiter ce type d'entité"""
|
||||
return entity_type == self.entity_type
|
||||
|
||||
class IPAddressRefiner(EntityRefiner):
|
||||
"""Raffineur pour les adresses IP"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("IP_ADDRESS")
|
||||
self.ipv4_regex = re.compile(
|
||||
r"\b(?:(?:25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]?\d)\.){3}"
|
||||
r"(?:25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]?\d)\b"
|
||||
)
|
||||
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
ent_text = text[start:end].strip()
|
||||
match = self.ipv4_regex.search(ent_text)
|
||||
|
||||
if not match:
|
||||
logger.warning(f"Invalid IP detected, skipping: '{ent_text}'")
|
||||
return None
|
||||
|
||||
true_ip = match.group(0)
|
||||
start_offset = ent_text.find(true_ip)
|
||||
|
||||
if start_offset == -1:
|
||||
logger.warning(f"IP regex match but cannot find substring position: '{ent_text}'")
|
||||
return None
|
||||
|
||||
new_start = start + start_offset
|
||||
new_end = new_start + len(true_ip)
|
||||
|
||||
logger.debug(f"Adjusted IP span: {start}-{end} => {new_start}-{new_end}")
|
||||
return (new_start, new_end)
|
||||
76
refiners/location_address_refiner.py
Normal file
76
refiners/location_address_refiner.py
Normal file
@@ -0,0 +1,76 @@
|
||||
from typing import List, Optional, Tuple
|
||||
from presidio_analyzer import RecognizerResult
|
||||
from abc import ABC, abstractmethod
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EntityRefiner(ABC):
|
||||
"""Classe de base pour le recadrage d'entités"""
|
||||
|
||||
def __init__(self, entity_type: str):
|
||||
self.entity_type = entity_type
|
||||
|
||||
@abstractmethod
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""
|
||||
Recadre une entité détectée
|
||||
|
||||
Args:
|
||||
text: Le texte complet
|
||||
start: Position de début de l'entité détectée
|
||||
end: Position de fin de l'entité détectée
|
||||
|
||||
Returns:
|
||||
Tuple (nouveau_start, nouveau_end) ou None si l'entité doit être ignorée
|
||||
"""
|
||||
pass
|
||||
|
||||
def should_process(self, entity_type: str) -> bool:
|
||||
"""Vérifie si ce raffineur doit traiter ce type d'entité"""
|
||||
return entity_type == self.entity_type
|
||||
|
||||
class LocationAddressRefiner(EntityRefiner):
|
||||
"""
|
||||
Refiner pour filtrer les doublons entre LOCATION et BE_ADDRESS/FR_ADDRESS.
|
||||
Ce refiner ne modifie pas les positions mais peut supprimer des entités.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("LOCATION") # Ne traite que les LOCATION
|
||||
self.address_entities = {'BE_ADDRESS', 'FR_ADDRESS'}
|
||||
self.location_entity = 'LOCATION'
|
||||
# Cache pour stocker les adresses détectées
|
||||
self._detected_addresses = []
|
||||
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""
|
||||
Vérifie si cette LOCATION fait partie d'une adresse déjà détectée.
|
||||
|
||||
Args:
|
||||
text: Le texte complet
|
||||
start: Position de début de la LOCATION
|
||||
end: Position de fin de la LOCATION
|
||||
|
||||
Returns:
|
||||
Tuple (start, end) si la location doit être conservée, None sinon
|
||||
"""
|
||||
location_text = text[start:end].strip().lower()
|
||||
|
||||
# Ignorer les locations trop courtes ou non significatives
|
||||
if len(location_text) <= 3 or location_text in ['tel', 'fax', 'gsm']:
|
||||
logger.debug(f"Ignoring short/insignificant location: '{location_text}'")
|
||||
return None
|
||||
|
||||
# Chercher des adresses dans le texte (simple heuristique)
|
||||
# Cette approche est limitée car on n'a accès qu'à une entité à la fois
|
||||
# Une meilleure approche serait de modifier l'architecture globale
|
||||
|
||||
# Pour l'instant, on garde toutes les locations valides
|
||||
# et on laisse un post-processing global gérer les doublons
|
||||
logger.debug(f"Keeping location: '{location_text}'")
|
||||
return (start, end)
|
||||
|
||||
def should_process(self, entity_type: str) -> bool:
|
||||
"""Ne traite que les entités LOCATION"""
|
||||
return entity_type == self.location_entity
|
||||
39
refiners/word_boundary_refiner.py
Normal file
39
refiners/word_boundary_refiner.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import re
|
||||
from typing import Optional, Tuple
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class WordBoundaryRefiner:
|
||||
"""Refiner pour étendre les entités aux limites de mots complets"""
|
||||
|
||||
def __init__(self):
|
||||
self.entity_type = "ALL" # S'applique à tous les types d'entités
|
||||
|
||||
def should_process(self, entity_type: str) -> bool:
|
||||
"""Ce refiner s'applique à tous les types d'entités"""
|
||||
return True
|
||||
|
||||
def refine(self, text: str, start: int, end: int) -> Optional[Tuple[int, int]]:
|
||||
"""Étend l'entité pour inclure le mot complet"""
|
||||
try:
|
||||
# Trouver le début du mot
|
||||
new_start = start
|
||||
while new_start > 0 and text[new_start - 1].isalnum():
|
||||
new_start -= 1
|
||||
|
||||
# Trouver la fin du mot
|
||||
new_end = end
|
||||
while new_end < len(text) and text[new_end].isalnum():
|
||||
new_end += 1
|
||||
|
||||
# Retourner les nouvelles positions si elles ont changé
|
||||
if new_start != start or new_end != end:
|
||||
logger.debug(f"Extended entity boundaries from [{start}:{end}] to [{new_start}:{new_end}]")
|
||||
return (new_start, new_end)
|
||||
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in WordBoundaryRefiner: {e}")
|
||||
return None
|
||||
Reference in New Issue
Block a user