Update app.py
This commit is contained in:
31
app.py
31
app.py
@@ -3,13 +3,15 @@ import logging
|
|||||||
import yaml
|
import yaml
|
||||||
from flask import Flask, request, jsonify, make_response
|
from flask import Flask, request, jsonify, make_response
|
||||||
|
|
||||||
|
# Import des classes nécessaires de Presidio
|
||||||
from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, PatternRecognizer, Pattern
|
from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, PatternRecognizer, Pattern
|
||||||
from presidio_analyzer.nlp_engine import NlpEngineProvider
|
from presidio_analyzer.nlp_engine import NlpEngineProvider
|
||||||
from presidio_analyzer.deny_list_recognizer import DenyListRecognizer
|
|
||||||
|
|
||||||
|
# Configuration du logging
|
||||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# --- CHARGEMENT MANUEL ET EXPLICITE DE LA 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")
|
||||||
logger.info(f"Loading configuration from: {CONFIG_FILE_PATH}")
|
logger.info(f"Loading configuration from: {CONFIG_FILE_PATH}")
|
||||||
|
|
||||||
@@ -18,31 +20,31 @@ try:
|
|||||||
with open(CONFIG_FILE_PATH, 'r', encoding='utf-8') as f:
|
with open(CONFIG_FILE_PATH, 'r', encoding='utf-8') as f:
|
||||||
config = yaml.safe_load(f)
|
config = yaml.safe_load(f)
|
||||||
logger.info("Configuration file loaded successfully.")
|
logger.info("Configuration file loaded successfully.")
|
||||||
except FileNotFoundError:
|
except Exception as e:
|
||||||
logger.error(f"Configuration file not found at {CONFIG_FILE_PATH}. Using default empty config.")
|
logger.exception(f"Could not load or parse configuration file at {CONFIG_FILE_PATH}")
|
||||||
except yaml.YAMLError as e:
|
# En cas d'échec, on continue avec une config vide pour ne pas planter, mais le service sera limité.
|
||||||
logger.error(f"Error parsing YAML configuration file: {e}. Using default empty config.")
|
config = {}
|
||||||
|
|
||||||
|
# On récupère les langues supportées depuis la config pour les utiliser partout
|
||||||
supported_languages_from_config = config.get("supported_languages", ["en"])
|
supported_languages_from_config = config.get("supported_languages", ["en"])
|
||||||
logger.info(f"Languages supported according to config: {supported_languages_from_config}")
|
logger.info(f"Languages supported according to config: {supported_languages_from_config}")
|
||||||
|
|
||||||
|
# Création du fournisseur de moteur NLP
|
||||||
logger.info("Creating NLP engine provider...")
|
logger.info("Creating NLP engine provider...")
|
||||||
nlp_engine_provider = NlpEngineProvider(nlp_configuration=config.get("nlp_engine_configuration"))
|
nlp_engine_provider = NlpEngineProvider(nlp_configuration=config.get("nlp_engine_configuration"))
|
||||||
nlp_engine = nlp_engine_provider.create_engine()
|
nlp_engine = nlp_engine_provider.create_engine()
|
||||||
logger.info(f"NLP engine created with models for: {nlp_engine.get_supported_languages()}")
|
logger.info(f"NLP engine created with models for: {nlp_engine.get_supported_languages()}")
|
||||||
|
|
||||||
# --- CORRECTION ICI ---
|
# Création du registre de recognizers
|
||||||
# On s'assure que le registry est initialisé avec les mêmes langues que le reste
|
|
||||||
logger.info("Creating and populating recognizer registry...")
|
logger.info("Creating and populating recognizer registry...")
|
||||||
registry = RecognizerRegistry()
|
registry = RecognizerRegistry()
|
||||||
registry.load_predefined_recognizers(languages=supported_languages_from_config) # On utilise la variable
|
# On initialise le registre avec TOUTES les langues supportées
|
||||||
logger.info(f"Recognizer registry loaded for languages: {supported_languages_from_config}")
|
registry.load_predefined_recognizers(languages=supported_languages_from_config)
|
||||||
|
|
||||||
# Ajout des recognizers personnalisés
|
# Ajout des recognizers personnalisés définis dans le YAML
|
||||||
custom_recognizers_conf = config.get("recognizers", [])
|
custom_recognizers_conf = config.get("recognizers", [])
|
||||||
for recognizer_conf in custom_recognizers_conf:
|
for recognizer_conf in custom_recognizers_conf:
|
||||||
patterns = [Pattern(name=p['name'], regex=p['regex'], score=p['score']) for p in recognizer_conf['patterns']]
|
patterns = [Pattern(name=p['name'], regex=p['regex'], score=p['score']) for p in recognizer_conf['patterns']]
|
||||||
|
|
||||||
custom_recognizer = PatternRecognizer(
|
custom_recognizer = PatternRecognizer(
|
||||||
supported_entity=recognizer_conf['entity_name'],
|
supported_entity=recognizer_conf['entity_name'],
|
||||||
name=recognizer_conf['name'],
|
name=recognizer_conf['name'],
|
||||||
@@ -50,16 +52,16 @@ for recognizer_conf in custom_recognizers_conf:
|
|||||||
patterns=patterns,
|
patterns=patterns,
|
||||||
context=recognizer_conf.get('context')
|
context=recognizer_conf.get('context')
|
||||||
)
|
)
|
||||||
|
|
||||||
registry.add_recognizer(custom_recognizer)
|
registry.add_recognizer(custom_recognizer)
|
||||||
logger.info(f"Loaded custom recognizer: {custom_recognizer.name}")
|
logger.info(f"Loaded custom recognizer: {custom_recognizer.name}")
|
||||||
|
|
||||||
# Préparation de l'allow_list
|
# Préparation de l'allow_list (simple liste de mots)
|
||||||
allow_list_config = config.get("allow_list", [])
|
allow_list_config = config.get("allow_list", [])
|
||||||
allow_list_terms = [item if isinstance(item, str) else item.get('text') for item in allow_list_config if item]
|
allow_list_terms = [item if isinstance(item, str) else item.get('text') for item in allow_list_config if item]
|
||||||
if allow_list_terms:
|
if allow_list_terms:
|
||||||
logger.info(f"Prepared {len(allow_list_terms)} terms for the allow list.")
|
logger.info(f"Prepared {len(allow_list_terms)} terms for the allow list.")
|
||||||
|
|
||||||
|
# Initialisation de l'application Flask
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
# Initialisation du moteur Presidio Analyzer
|
# Initialisation du moteur Presidio Analyzer
|
||||||
@@ -67,7 +69,7 @@ logger.info("Initializing AnalyzerEngine with custom configuration...")
|
|||||||
analyzer = AnalyzerEngine(
|
analyzer = AnalyzerEngine(
|
||||||
nlp_engine=nlp_engine,
|
nlp_engine=nlp_engine,
|
||||||
registry=registry,
|
registry=registry,
|
||||||
supported_languages=supported_languages_from_config, # On utilise la variable ici aussi
|
supported_languages=supported_languages_from_config, # On s'assure de la cohérence ici aussi
|
||||||
default_score_threshold=config.get("ner_model_configuration", {}).get("confidence_threshold", {}).get("default", 0.35)
|
default_score_threshold=config.get("ner_model_configuration", {}).get("confidence_threshold", {}).get("default", 0.35)
|
||||||
)
|
)
|
||||||
logger.info("AnalyzerEngine initialized successfully.")
|
logger.info("AnalyzerEngine initialized successfully.")
|
||||||
@@ -82,6 +84,7 @@ def analyze_text():
|
|||||||
if not text_to_analyze:
|
if not text_to_analyze:
|
||||||
return jsonify({"error": "text field is missing or empty"}), 400
|
return jsonify({"error": "text field is missing or empty"}), 400
|
||||||
|
|
||||||
|
# On passe directement la liste de mots à ignorer au paramètre 'allow_list'
|
||||||
results = analyzer.analyze(
|
results = analyzer.analyze(
|
||||||
text=text_to_analyze,
|
text=text_to_analyze,
|
||||||
language=language,
|
language=language,
|
||||||
|
|||||||
Reference in New Issue
Block a user