115 lines
4.2 KiB
Python
115 lines
4.2 KiB
Python
import os
|
|
import re
|
|
import logging
|
|
from flask import Flask, request, jsonify, make_response
|
|
|
|
from presidio_analyzer import AnalyzerEngineProvider
|
|
|
|
# Config du logging
|
|
logging.basicConfig(level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
logger = logging.getLogger(__name__)
|
|
|
|
app = Flask(__name__)
|
|
|
|
# Initialisation Presidio Analyzer via Provider
|
|
analyzer = None
|
|
try:
|
|
logger.info("--- Presidio Analyzer Service Starting ---")
|
|
CONFIG_FILE_PATH = os.environ.get("PRESIDIO_ANALYZER_CONFIG_FILE", "conf/default.yaml")
|
|
provider = AnalyzerEngineProvider(analyzer_engine_conf_file=CONFIG_FILE_PATH)
|
|
analyzer = provider.create_engine()
|
|
logger.info(f"Analyzer ready. Supported languages: {analyzer.supported_languages}")
|
|
except Exception as e:
|
|
logger.exception("Error during AnalyzerEngine initialization.")
|
|
analyzer = None
|
|
|
|
|
|
# Regex IBAN strict : 2 lettres, 2 chiffres, puis 4 groupes de 4 alphanum (minimum),
|
|
# avec optional whitespace between groups
|
|
IBAN_REGEX = re.compile(r"\b[A-Z]{2}[0-9]{2}(?:\s?[A-Z0-9]{4}){4,7}\b", re.IGNORECASE)
|
|
|
|
# Labels / titres à exclure de l'anonymisation (en minuscules pour normalisation)
|
|
IGNORE_LABELS = {
|
|
"témoins",
|
|
"témoins clés",
|
|
"coordonnées",
|
|
"coordonnées bancaires",
|
|
"contexte financier",
|
|
"données sensibles",
|
|
"contexte",
|
|
"montrent",
|
|
"bénéficiaire"
|
|
# ajouter d'autres labels ici si besoin
|
|
}
|
|
|
|
def normalize_label(txt):
|
|
return txt.strip().lower()
|
|
|
|
|
|
@app.route('/analyze', methods=['POST'])
|
|
def analyze_text():
|
|
if not analyzer:
|
|
return jsonify({"error": "Analyzer engine is not available. Check startup logs."}), 500
|
|
|
|
try:
|
|
data = request.get_json(force=True)
|
|
text_to_analyze = data.get("text", "")
|
|
language = data.get("language", "fr")
|
|
|
|
if not text_to_analyze:
|
|
return jsonify({"error": "text field is missing or empty"}), 400
|
|
|
|
results = analyzer.analyze(
|
|
text=text_to_analyze,
|
|
language=language
|
|
)
|
|
|
|
filtered_results = []
|
|
for res in results:
|
|
ent_text = text_to_analyze[res.start:res.end].strip()
|
|
ent_text_norm = normalize_label(ent_text)
|
|
|
|
# 1. Ignorer les entités correspondant exactement aux labels/titres à préserver
|
|
if ent_text_norm in IGNORE_LABELS:
|
|
logger.debug(f"Skip anonymizing label: '{ent_text}'")
|
|
continue
|
|
|
|
# 2. Si entité de type IBAN, resserrer la sélection strictement au format IBAN
|
|
if res.entity_type == "IBAN":
|
|
match = IBAN_REGEX.search(ent_text)
|
|
if match:
|
|
true_iban = match.group(0)
|
|
# Recalcule start/end dans le texte original
|
|
start_offset = ent_text.find(true_iban)
|
|
if start_offset != -1:
|
|
old_start = res.start
|
|
old_end = res.end
|
|
res.start += start_offset
|
|
res.end = res.start + len(true_iban)
|
|
ent_text = true_iban
|
|
logger.debug(f"Correct IBAN span from ({old_start}-{old_end}) to ({res.start}-{res.end}): '{ent_text}'")
|
|
else:
|
|
# Aucun start trouvé (peu probable), garder tel quel
|
|
logger.warning(f"Could not find exact IBAN substring in entity text: '{ent_text}'")
|
|
else:
|
|
# Pas de correspondance valide au regex IBAN, on peut choisir d'ignorer ou garder tel quel
|
|
logger.warning(f"Entity IBAN does not match IBAN regex: '{ent_text}'")
|
|
|
|
filtered_results.append(res)
|
|
|
|
response_data = [res.to_dict() for res in filtered_results]
|
|
|
|
# **Important :** retourne uniquement les entités à anonymiser (sans labels exclus)
|
|
return make_response(jsonify(response_data), 200)
|
|
|
|
except Exception as e:
|
|
logger.exception(f"Error during analysis for language '{language}'.")
|
|
if "No matching recognizers" in str(e):
|
|
return jsonify({"error": f"No recognizers available for language '{language}'."}), 400
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host='0.0.0.0', port=5001)
|