Actualiser app.py

This commit is contained in:
2025-08-03 20:29:50 +00:00
parent 43b1b5100f
commit becbbcfaaa

31
app.py
View File

@@ -1,11 +1,11 @@
import os import os
import re import re
import logging import logging
import yaml # ### AJOUT ### Nécessaire pour charger la configuration manuellement import yaml
from flask import Flask, request, jsonify, make_response from flask import Flask, request, jsonify, make_response
# ### AJOUT ### Import des classes nécessaires pour l'anonymisation # Ces imports sont suffisants et corrects pour votre configuration actuelle:
from presidio_analyzer import AnalyzerEngine, RecognizerResult, AnalyzerEngineProvider from presidio_analyzer import AnalyzerEngine, RecognizerResult, AnalyzerEngineProvider
from presidio_anonymizer import AnonymizerEngine from presidio_anonymizer import AnonymizerEngine
@@ -17,26 +17,25 @@ app = Flask(__name__)
# --- Initialisation combinée de l'Analyzer et de l'Anonymizer --- # --- Initialisation combinée de l'Analyzer et de l'Anonymizer ---
analyzer = None analyzer = None
anonymizer = None anonymizer = None
try: try:
logger.info("--- Presidio Service Starting ---") logger.info("--- Presidio Service Starting ---")
# On récupère le chemin du fichier de configuration
CONFIG_FILE_PATH = os.environ.get("PRESIDIO_ANALYZER_CONFIG_FILE", "conf/default.yaml") CONFIG_FILE_PATH = os.environ.get("PRESIDIO_ANALYZER_CONFIG_FILE", "conf/default.yaml")
if not os.path.exists(CONFIG_FILE_PATH): if not os.path.exists(CONFIG_FILE_PATH):
raise FileNotFoundError(f"Configuration file not found at: {CONFIG_FILE_PATH}") raise FileNotFoundError(f"Configuration file not found at: {CONFIG_FILE_PATH}")
# On charge le fichier YAML en mémoire
with open(CONFIG_FILE_PATH, 'r') as f: with open(CONFIG_FILE_PATH, 'r') as f:
config = yaml.safe_load(f) config = yaml.safe_load(f)
# 1. Créer l'Analyzer Engine en utilisant le provider et la configuration chargée # 1. Créer l'Analyzer Engine en utilisant le provider et la configuration chargée
# Le provider sait comment lire la configuration pour l'analyzer # C'est cette ligne qui utilise AnalyzerEngineProvider, il n'y a donc pas besoin
# d'importer NlpEngineProvider séparément.
provider = AnalyzerEngineProvider(analyzer_engine_conf=config) provider = AnalyzerEngineProvider(analyzer_engine_conf=config)
analyzer = provider.create_engine() analyzer = provider.create_engine()
# 2. ### AJOUT ### Créer l'Anonymizer Engine en lui passant sa section de configuration # 2. Créer l'Anonymizer Engine en lui passant sa section de configuration
anonymizer_config = config.get("anonymizer_config", {}) anonymizer_config = config.get("anonymizer_config", {})
anonymizer = AnonymizerEngine(anonymizer_config=anonymizer_config) anonymizer = AnonymizerEngine(anonymizer_config=anonymizer_config)
@@ -58,7 +57,7 @@ IPV4_REGEX = re.compile(
r"(?:25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]?\d)\b" r"(?:25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]?\d)\b"
) )
# Liste des labels/phrases à exclure danonymisation # Liste des labels/phrases à exclure danonymisation (en minuscules) (INCHANGÉ)
IGNORE_LABELS = { IGNORE_LABELS = {
"témoins", "témoins",
"témoins clés", "témoins clés",
@@ -76,9 +75,9 @@ IGNORE_LABELS = {
def normalize_label(text: str) -> str: def normalize_label(text: str) -> str:
return text.strip().lower() return text.strip().lower()
# ========================= # =====================================================================
# ENDPOINT /analyze BASIQUE # VOTRE ENDPOINT /analyze ORIGINAL - SANS AUCUN CHANGEMENT
# ========================= # =====================================================================
@app.route("/analyze", methods=["POST"]) @app.route("/analyze", methods=["POST"])
def analyze_text(): def analyze_text():
if not analyzer: if not analyzer:
@@ -138,10 +137,9 @@ def analyze_text():
logger.exception("Error processing analysis") logger.exception("Error processing analysis")
return jsonify({"error": str(e)}), 500 return jsonify({"error": str(e)}), 500
# ============================================ # =====================================================================
# ENDPOINT /anonymize QUI FAIT LE REMPLACEMENT # NOUVEL ENDPOINT /anonymize QUI FAIT LE REMPLACEMENT
# ============================================ # =====================================================================
@app.route("/anonymize", methods=["POST"]) @app.route("/anonymize", methods=["POST"])
def anonymize_text(): def anonymize_text():
if not analyzer or not anonymizer: if not analyzer or not anonymizer:
@@ -159,8 +157,6 @@ def anonymize_text():
analyzer_results = analyzer.analyze(text=text_to_process, language=language) analyzer_results = analyzer.analyze(text=text_to_process, language=language)
# Étape 2 : Anonymiser le texte en utilisant les résultats de l'analyse # Étape 2 : Anonymiser le texte en utilisant les résultats de l'analyse
# L'AnonymizerEngine va utiliser la config 'anonymizer_config' pour faire les remplacements
anonymized_result = anonymizer.anonymize( anonymized_result = anonymizer.anonymize(
text=text_to_process, text=text_to_process,
analyzer_results=analyzer_results analyzer_results=analyzer_results
@@ -177,5 +173,4 @@ def anonymize_text():
# DÉMARRAGE DE L'APPLICATION FLASK (INCHANGÉ) # DÉMARRAGE DE L'APPLICATION FLASK (INCHANGÉ)
# ===================================================================== # =====================================================================
if __name__ == "__main__": if __name__ == "__main__":
# Pour le déploiement, il est préférable d'utiliser un serveur WSGI comme Gunicorn
app.run(host="0.0.0.0", port=5001) app.run(host="0.0.0.0", port=5001)