colandix 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
colandix/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ from colandix.exceptions import ColandixBlockedError
2
+ from colandix.pipeline import GuardPipeline
3
+ from colandix.profiles.loader import get_profile_metadata, list_profiles
4
+ from colandix.redaction import REDACTION_TAGS, get_redaction_tag
5
+ from colandix.result import Action, PipelineConfig, ScanDirection, ScanResult
6
+
7
+ __version__ = "0.1.0"
8
+ __author__ = "Gros Gradient"
9
+
10
+ __all__ = [
11
+ "GuardPipeline",
12
+ "ColandixBlockedError",
13
+ "ScanResult",
14
+ "Action",
15
+ "ScanDirection",
16
+ "PipelineConfig",
17
+ "list_profiles",
18
+ "get_profile_metadata",
19
+ "REDACTION_TAGS",
20
+ "get_redaction_tag",
21
+ ]
colandix/compliance.py ADDED
@@ -0,0 +1,185 @@
1
+ from datetime import datetime, timezone
2
+
3
+ from colandix.detectors.base import BaseDetector
4
+ from colandix.redaction import REDACTION_TAGS
5
+ from colandix.result import Action
6
+
7
+ ANSSI_PA102_REQUIREMENTS: dict[str, dict] = {
8
+ "R25": {
9
+ "titre": "Filtrage des entrées et sorties",
10
+ "description": (
11
+ "Mettre en place des mécanismes de filtrage "
12
+ "des données en entrée et en sortie du modèle"
13
+ ),
14
+ "obligatoire": True,
15
+ },
16
+ "R26": {
17
+ "titre": "Maîtrise des interactions applicatives",
18
+ "description": (
19
+ "Maîtriser les interactions du système d'IA "
20
+ "avec d'autres applications du SI"
21
+ ),
22
+ "obligatoire": True,
23
+ },
24
+ "R27": {
25
+ "titre": "Contrôle humain des actions critiques",
26
+ "description": (
27
+ "Proscrire les actions automatisées critiques " "sans validation humaine"
28
+ ),
29
+ "obligatoire": True,
30
+ },
31
+ "R29": {
32
+ "titre": "Journalisation des interactions",
33
+ "description": (
34
+ "Journaliser les interactions avec le système d'IA générative"
35
+ ),
36
+ "obligatoire": True,
37
+ },
38
+ "R31": {
39
+ "titre": "Sécurisation des accès aux modules critiques",
40
+ "description": (
41
+ "Contrôler les accès aux composants critiques " "du système d'IA"
42
+ ),
43
+ "obligatoire": False,
44
+ },
45
+ "R34": {
46
+ "titre": "Hébergement souverain",
47
+ "description": (
48
+ "Garantir qu'aucune donnée ne transite vers " "un tiers non maîtrisé"
49
+ ),
50
+ "obligatoire": False,
51
+ },
52
+ }
53
+
54
+
55
+ def generate_report(
56
+ detectors: list[BaseDetector], profile_name: str, version: str = "0.1.0"
57
+ ) -> dict:
58
+ """
59
+ Génère un rapport de conformité ANSSI-PA-102 basé sur les détecteurs actifs.
60
+ """
61
+ # Étape 1 — Construire la carte de couverture
62
+ coverage: dict[str, list[str]] = {}
63
+ for detector in detectors:
64
+ ref = detector.config.anssi_ref
65
+ if ref not in coverage:
66
+ coverage[ref] = []
67
+ coverage[ref].append(detector.config.name)
68
+
69
+ # Étape 2 — R29 est couverte par le logger (by design)
70
+ if "R29" not in coverage:
71
+ coverage["R29"] = ["ColandixLogger"]
72
+
73
+ # Étape 3 — R34 est couverte par conception (zéro appel externe)
74
+ if "R34" not in coverage:
75
+ coverage["R34"] = ["by design — zéro appel externe"]
76
+
77
+ # Étape 4 — R27 est couverte si au moins un détecteur a Action.HUMAN_REVIEW
78
+ human_review_detectors = [
79
+ d.config.name for d in detectors if d.config.action == Action.HUMAN_REVIEW
80
+ ]
81
+ if human_review_detectors and "R27" not in coverage:
82
+ coverage["R27"] = human_review_detectors
83
+
84
+ # Étape 5 — Construire les exigences
85
+ exigences = {}
86
+ for ref, req in ANSSI_PA102_REQUIREMENTS.items():
87
+ detecteurs_couvrants = coverage.get(ref, [])
88
+ exigences[ref] = {
89
+ "titre": req["titre"],
90
+ "description": req["description"],
91
+ "obligatoire": req["obligatoire"],
92
+ "status": "CONFORME" if detecteurs_couvrants else "NON COUVERT",
93
+ "detecteurs": detecteurs_couvrants,
94
+ }
95
+
96
+ # Étape 6 — Conformité globale
97
+ if exigences["R25"]["status"] == "NON COUVERT":
98
+ conformite_globale = "NON CONFORME"
99
+ elif all(
100
+ exigences[ref]["status"] == "CONFORME"
101
+ for ref, req in ANSSI_PA102_REQUIREMENTS.items()
102
+ if req["obligatoire"]
103
+ ):
104
+ conformite_globale = "CONFORME"
105
+ else:
106
+ conformite_globale = "PARTIELLE"
107
+
108
+ # Étape 7 — Recommandations
109
+ recommandations = []
110
+ for ref, req in ANSSI_PA102_REQUIREMENTS.items():
111
+ if req["obligatoire"] and exigences[ref]["status"] == "NON COUVERT":
112
+ if ref == "R27":
113
+ recommandations.append(
114
+ "R27 non couverte : ajouter un détecteur avec "
115
+ "action=human_review dans le profil YAML"
116
+ )
117
+ elif ref == "R25":
118
+ recommandations.append(
119
+ "R25 non couverte : ajouter au minimum un détecteur "
120
+ "de type regex ou injection"
121
+ )
122
+ else:
123
+ recommandations.append(
124
+ f"{ref} non couverte : voir ANSSI-PA-102 pour les "
125
+ f"mesures requises"
126
+ )
127
+
128
+ return {
129
+ "titre": "Rapport de conformité ANSSI-PA-102",
130
+ "generated_at": datetime.now(timezone.utc).isoformat(),
131
+ "colandix_version": version,
132
+ "profil": profile_name,
133
+ "appels_externes": 0,
134
+ "souverain": True,
135
+ "nb_detecteurs_actifs": len([d for d in detectors if d.config.enabled]),
136
+ "exigences": exigences,
137
+ "conformite_globale": conformite_globale,
138
+ "recommandations": recommandations,
139
+ "sanitization": {
140
+ "tags_typés": True,
141
+ "tags_disponibles": list(REDACTION_TAGS.keys()),
142
+ "injection_sanitizable": False,
143
+ "entropy_sanitizable": False,
144
+ },
145
+ }
146
+
147
+
148
+ def print_report(report: dict):
149
+ """Affiche le rapport lisiblement dans le terminal."""
150
+ print("═" * 50)
151
+ print(" RAPPORT DE CONFORMITÉ ANSSI-PA-102")
152
+ print(f" colandix v{report['colandix_version']} — Gros Gradient")
153
+ print("═" * 50)
154
+ print(f"Profil : {report['profil']}")
155
+ print(
156
+ f"Souverain : {'✓' if report['souverain'] else '✗'} "
157
+ f"({report['appels_externes']} appel externe)"
158
+ )
159
+ print(f"Détecteurs : {report['nb_detecteurs_actifs']} actifs")
160
+ print("\nEXIGENCES :")
161
+
162
+ for ref, req in report["exigences"].items():
163
+ icon = "✓" if req["status"] == "CONFORME" else "-"
164
+ # Tronquage des détecteurs
165
+ detects = req["detecteurs"]
166
+ if not detects:
167
+ detects_str = "[non couvert]"
168
+ else:
169
+ if len(detects) > 3:
170
+ detects_str = f"[{', '.join(detects[:3])}, ...]"
171
+ else:
172
+ detects_str = f"[{', '.join(detects)}]"
173
+
174
+ print(f" {ref} {icon} {req['titre']:<30} {detects_str}")
175
+
176
+ print(f"\nCONFORMITÉ GLOBALE : {report['conformite_globale']}")
177
+ print("─" * 50)
178
+
179
+ if report["recommandations"]:
180
+ print("RECOMMANDATIONS :")
181
+ for rec in report["recommandations"]:
182
+ print(f" • {rec}")
183
+ print("═" * 50)
184
+ else:
185
+ print("═" * 50)
@@ -0,0 +1 @@
1
+ # __init__.py — Initialisation du sous-module detectors
@@ -0,0 +1,123 @@
1
+ # base.py — Classe de base et interface pour tous les détecteurs
2
+
3
+ import functools
4
+ from abc import ABC, abstractmethod
5
+ from dataclasses import dataclass, field
6
+ from typing import Optional
7
+
8
+ from colandix.result import Action, DetectionEvent
9
+
10
+
11
+ @dataclass
12
+ class DetectorConfig:
13
+ """Configuration d'un détecteur individuel, lue depuis le YAML."""
14
+ name: str
15
+ action: Action
16
+ weight: float = 1.0
17
+ enabled: bool = True
18
+ anssi_ref: str = "R25"
19
+ extra: dict = field(default_factory=dict)
20
+
21
+ def __post_init__(self) -> None:
22
+ if not (0.0 <= self.weight <= 1.0):
23
+ raise ValueError(f"weight doit être entre 0.0 et 1.0, reçu : {self.weight}")
24
+
25
+
26
+ class DetectorError(Exception):
27
+ """Exception levée en cas d'erreur interne d'un détecteur."""
28
+ def __init__(self, detector_name: str, original_error: Exception):
29
+ self.detector_name = detector_name
30
+ self.original_error = original_error
31
+ super().__init__(
32
+ f"Erreur dans le détecteur '{detector_name}' : {original_error}"
33
+ )
34
+
35
+
36
+ def safe_analyze(func):
37
+ """
38
+ Décorateur qui wrape la méthode analyze() pour capturer les exceptions
39
+ et retourner un événement de secours, évitant ainsi le crash du pipeline.
40
+ """
41
+ @functools.wraps(func)
42
+ def wrapper(self: 'BaseDetector', text: str, *args, **kwargs) -> DetectionEvent:
43
+ try:
44
+ return func(self, text, *args, **kwargs)
45
+ except Exception as e:
46
+ print(f"[colandix] ERREUR détecteur '{self.config.name}': {e}")
47
+ # 7 chars pour "ERROR: " + 43 chars max = 50 chars max
48
+ evidence_msg = "ERROR: " + str(e)[:43]
49
+ return DetectionEvent(
50
+ detector_name=self.config.name,
51
+ detector_type=self.__class__.__name__,
52
+ matched=False,
53
+ score=0.0,
54
+ action=Action.PASS,
55
+ evidence=evidence_msg,
56
+ anssi_ref=self.config.anssi_ref,
57
+ )
58
+ return wrapper
59
+
60
+
61
+ class BaseDetector(ABC):
62
+ """
63
+ Classe de base abstraite pour tous les détecteurs de colandix.
64
+ """
65
+ def __init__(self, config: DetectorConfig):
66
+ self.config = config
67
+
68
+ def is_enabled(self) -> bool:
69
+ """Retourne True si le détecteur est activé dans sa configuration."""
70
+ return self.config.enabled
71
+
72
+ @abstractmethod
73
+ def analyze(self, text: str) -> DetectionEvent:
74
+ """
75
+ Analyse le texte fourni.
76
+
77
+ - Appelée sur chaque requête en production : doit être rapide
78
+ - Ne doit JAMAIS faire d'appel réseau (souveraineté colandix)
79
+ - Doit TOUJOURS retourner un DetectionEvent même si rien détecté
80
+ - Le score retourné doit être entre 0.0 et 1.0
81
+ """
82
+ pass
83
+
84
+ def find_all_candidates(self, text: str) -> list[dict]:
85
+ """
86
+ Extrait TOUS les candidats potentiels détectés par ce détecteur.
87
+ Retourne une liste de dict : [{"matched": "...", "score": 1.0, "reason": "..."}]
88
+ """
89
+ return []
90
+
91
+ def _make_event(
92
+ self,
93
+ matched: bool,
94
+ score: float,
95
+ evidence: Optional[str] = None,
96
+ trigger_type: Optional[str] = None,
97
+ match_text: Optional[str] = None,
98
+ ) -> DetectionEvent:
99
+ """Helper protégé pour construire un DetectionEvent standardisé."""
100
+
101
+ if evidence is not None and len(evidence) > 50:
102
+ evidence = evidence[:50]
103
+
104
+ action = self.config.action if matched else Action.PASS
105
+ tt = trigger_type if matched else None
106
+ mt = match_text if matched else None
107
+
108
+ return DetectionEvent(
109
+ detector_name=self.config.name,
110
+ detector_type=self.__class__.__name__,
111
+ matched=matched,
112
+ score=score,
113
+ action=action,
114
+ evidence=evidence,
115
+ trigger_type=tt,
116
+ anssi_ref=self.config.anssi_ref,
117
+ match_text=mt,
118
+ )
119
+
120
+ def __repr__(self) -> str:
121
+ return (f"{self.__class__.__name__}(name='{self.config.name}', "
122
+ f"action='{self.config.action.value}', enabled={self.config.enabled})")
123
+
@@ -0,0 +1,336 @@
1
+ # entropy.py — Détecteur basé sur l'entropie (ex: obfuscation, clés crypto)
2
+
3
+ import math
4
+ import re
5
+ from typing import Optional
6
+
7
+ from colandix.detectors.base import BaseDetector, DetectorConfig, safe_analyze
8
+ from colandix.result import DetectionEvent
9
+
10
+
11
+ class EntropyDetector(BaseDetector):
12
+ """
13
+ Détecteur identifiant des secrets par analyse d'entropie de Shannon.
14
+ Un secret aléatoire (clé API, token) a une distribution de caractères
15
+ uniforme, ce qui donne une entropie élevée (ex: > 4.5 bits).
16
+ Complété par détection de contexte (mot-clé + valeur) et ratio voyelles.
17
+ """
18
+
19
+ VOYELLES = frozenset("aeiouyAEIOUYàâéèêëîïôùûüœæ")
20
+
21
+ CONTEXT_PATTERNS = [
22
+ # Mot-clé + := ou = uniquement (pas d'espace seul comme séparateur).
23
+ # Aligné spec « secrets » : séparateur structurel ; jeton / identifiant / mdp et
24
+ # « mot de passe » (tiret, underscore ou espace) en bonus FR.
25
+ re.compile(
26
+ r"\b(?:password|passwd|pwd|secret|token|api[_-]?key|apikey"
27
+ r"|access[_-]?key|private[_-]?key|client[_-]?secret"
28
+ r"|auth[_-]?token|refresh[_-]?token|bearer|passphrase"
29
+ r"|credential|mdp|mot[_\s]de[_\s]passe|clef?|jeton|identifiant)\s*[:=]\s*"
30
+ r'["\']?(\S{8,})["\']?',
31
+ re.IGNORECASE | re.UNICODE,
32
+ ),
33
+ re.compile(
34
+ r"\bAuthorization\s*:\s*(?:Bearer|Token|Basic)\s+(\S{8,})",
35
+ re.IGNORECASE | re.UNICODE,
36
+ ),
37
+ re.compile(
38
+ r'["\'](?:password|secret|token|api_key|apikey|credential)'
39
+ r'["\']\s*:\s*["\'](\S{8,})["\']',
40
+ re.IGNORECASE | re.UNICODE,
41
+ ),
42
+ # Variable d'environnement SCREAMING_SNAKE (au moins 3 car. après la 1re lettre)
43
+ re.compile(
44
+ r"\b[A-Z][A-Z0-9_]{2,}(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD"
45
+ r"|CREDENTIAL|AUTH|API|PWD)\s*=\s*[\"\']?(\S{8,})[\"\']?"
46
+ ),
47
+ ]
48
+
49
+ ENTROPY_WHITELIST_PATTERNS = [
50
+ re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}", re.IGNORECASE), # UUID
51
+ re.compile(r"^https?://", re.IGNORECASE), # URL
52
+ re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE), # MD5 pur
53
+ ]
54
+
55
+ def __init__(self, config: DetectorConfig):
56
+ super().__init__(config)
57
+ self._threshold = float(self.config.extra.get("threshold", 4.5))
58
+ self._min_length = int(self.config.extra.get("min_length", 20))
59
+ self._max_length = int(self.config.extra.get("max_length", 500))
60
+
61
+ # Construit le pattern d'extraction de tokens
62
+ self._token_pattern = re.compile(
63
+ rf"[a-zA-Z0-9+/=_\-\.]{{{self._min_length},{self._max_length}}}", re.UNICODE
64
+ )
65
+
66
+ def _shannon_entropy(self, s: str) -> float:
67
+ """Calcule l'entropie de Shannon d'une chaîne de caractères."""
68
+ if not s or len(s) <= 1:
69
+ return 0.0
70
+
71
+ counts: dict[str, int] = {}
72
+ for char in s:
73
+ counts[char] = counts.get(char, 0) + 1
74
+
75
+ length = len(s)
76
+ entropy = 0.0
77
+ for count in counts.values():
78
+ p = count / length
79
+ entropy -= p * math.log2(p)
80
+
81
+ return entropy
82
+
83
+ def _extract_tokens(self, text: str) -> list[str]:
84
+ """Extrait les tokens candidats du texte."""
85
+ tokens = []
86
+ for match in self._token_pattern.finditer(text):
87
+ token = match.group(0)
88
+ if self._min_length <= len(token) <= self._max_length:
89
+ tokens.append(token)
90
+ return tokens
91
+
92
+ def _detect_context(self, text: str) -> tuple[bool, Optional[str]]:
93
+ """
94
+ Mot-clé de secret suivi d'une valeur.
95
+ Retourne (True, valeur[:30]) ou (False, None).
96
+ """
97
+ for pattern in self.CONTEXT_PATTERNS:
98
+ m = pattern.search(text)
99
+ if m:
100
+ val = m.group(1)
101
+ if val:
102
+ return True, val[:30]
103
+ return False, None
104
+
105
+ def _ratio_voyelles(self, s: str) -> float:
106
+ """
107
+ Ratio voyelles / lettres totales. 0.0 si aucune lettre.
108
+ """
109
+ lettres = [c for c in s if c.isalpha()]
110
+ if not lettres:
111
+ return 0.0
112
+ return sum(1 for c in lettres if c in self.VOYELLES) / len(lettres)
113
+
114
+ def _score_complexite(self, token: str) -> float:
115
+ """
116
+ Score de complexité structurelle (types de caractères × longueur).
117
+ """
118
+ if len(token) < 8 or " " in token:
119
+ return 0.0
120
+
121
+ has_lower = any("a" <= c <= "z" for c in token)
122
+ has_upper = any("A" <= c <= "Z" for c in token)
123
+ has_digit = any("0" <= c <= "9" for c in token)
124
+ has_special = any(
125
+ not (("a" <= c <= "z") or ("A" <= c <= "Z") or ("0" <= c <= "9"))
126
+ for c in token
127
+ )
128
+
129
+ n_types = sum([has_lower, has_upper, has_digit, has_special])
130
+ if n_types <= 1:
131
+ score_base = 0.0
132
+ elif n_types == 2:
133
+ score_base = 0.25
134
+ elif n_types == 3:
135
+ score_base = 0.60
136
+ else:
137
+ score_base = 0.85
138
+
139
+ ln = len(token)
140
+ if ln <= 11:
141
+ mult = 0.6
142
+ elif ln <= 19:
143
+ mult = 0.8
144
+ else:
145
+ mult = 1.0
146
+
147
+ return score_base * mult
148
+
149
+ def analyze_token(self, token: str) -> float:
150
+ """Retourne l'entropie brute de Shannon d'un token."""
151
+ return self._shannon_entropy(token)
152
+
153
+ @safe_analyze
154
+ def analyze(self, text: str) -> DetectionEvent:
155
+ """
156
+ Détecte les secrets en combinant plusieurs signaux :
157
+ 1. Contexte (mot-clé + valeur) — signal le plus fiable
158
+ 2. Entropie de Shannon — signal principal existant
159
+ 4. Complexité structurelle (types de caractères × longueur)
160
+ 5. Zone « grise » : entropie légèrement sous le seuil mais jeton long
161
+ et forte complexité (clés avec caractères répétés, Shannon modéré)
162
+
163
+ Ne fait jamais d'appel réseau. 100% local.
164
+ """
165
+ context_found, context_value = self._detect_context(text)
166
+ if context_found and context_value is not None:
167
+ return self._make_event(
168
+ matched=True,
169
+ score=1.0,
170
+ evidence=f"contexte: {context_value}",
171
+ trigger_type="PASSWORD",
172
+ )
173
+
174
+ tokens = self._extract_tokens(text)
175
+ best_score = 0.0
176
+ best_evidence: Optional[str] = None
177
+
178
+ # Entropie Shannon sous le seuil mais proche : jeton long avec forte
179
+ # hétérogénéité (types de caractères) — ex. clés avec répétitions
180
+ # (entropie mesurée basse) mais toujours « random-looking ».
181
+ gray_entropy_delta = 0.75
182
+ gray_min_complexity = 0.60
183
+
184
+ for token in tokens:
185
+ entropy = self._shannon_entropy(token)
186
+
187
+ for whitelist_pattern in self.ENTROPY_WHITELIST_PATTERNS:
188
+ if whitelist_pattern.search(token):
189
+ entropy = entropy / 2.0
190
+ break
191
+
192
+ score_complexite = self._score_complexite(token)
193
+ rv = self._ratio_voyelles(token)
194
+
195
+ gray_structural = (
196
+ entropy > self._threshold - gray_entropy_delta
197
+ and entropy <= self._threshold
198
+ and len(token) >= self._min_length
199
+ and score_complexite >= gray_min_complexity
200
+ )
201
+
202
+ if entropy <= self._threshold:
203
+ if not gray_structural:
204
+ continue
205
+ score_final = 0.75
206
+ best_evidence = (
207
+ f"token:{token[:15]}.. e:{entropy:.2f} "
208
+ f"c:{score_complexite:.2f} gray"
209
+ )
210
+ best_score = max(best_score, score_final)
211
+ continue
212
+
213
+ score_entropie = min(
214
+ (entropy - self._threshold) / (6.0 - self._threshold),
215
+ 1.0,
216
+ )
217
+ score_entropie = max(score_entropie, 0.0)
218
+
219
+ if rv < 0.10:
220
+ score_final = min(score_entropie * 1.20, 1.0)
221
+ elif rv > 0.35:
222
+ score_final = score_entropie * 0.60
223
+ else:
224
+ score_final = score_entropie
225
+
226
+ score_combine = max(
227
+ score_final,
228
+ score_complexite,
229
+ (score_final + score_complexite) / 2,
230
+ )
231
+ score_final = min(score_combine, 1.0)
232
+
233
+ # Au-dessus du seuil d'entropie + jeton hétérogène (ex. clé sans préfixe
234
+ # sk-) : le score combiné restait ~0,6 (review) malgré un signal fort.
235
+ if (
236
+ entropy > self._threshold
237
+ and score_complexite >= 0.55
238
+ and len(token) >= self._min_length
239
+ ):
240
+ score_final = max(score_final, 0.90)
241
+
242
+ if score_final > best_score:
243
+ best_score = score_final
244
+ # Format compact pour tenir dans les 50 chars d'evidence
245
+ best_evidence = f"token:{token[:15]}.. e:{entropy:.2f} v:{rv:.2f}"
246
+ if score_complexite > 0.30:
247
+ best_evidence += f" c:{score_complexite:.2f}"
248
+
249
+ if best_score > 0 and best_evidence:
250
+ return self._make_event(
251
+ matched=True,
252
+ score=best_score,
253
+ evidence=best_evidence,
254
+ trigger_type="TOKEN",
255
+ )
256
+
257
+ return self._make_event(matched=False, score=0.0)
258
+ def find_all_candidates(self, text: str) -> list[dict]:
259
+ """Retourne TOUS les candidats détectés (contexte et entropie)."""
260
+ candidates = []
261
+
262
+ # 1. Contexte
263
+ for pattern in self.CONTEXT_PATTERNS:
264
+ for m in pattern.finditer(text):
265
+ val = m.group(1)
266
+ if val:
267
+ candidates.append({
268
+ "matched": val,
269
+ "score": 1.0,
270
+ "reason": "contexte"
271
+ })
272
+
273
+ # 2. Tokens (Entropie)
274
+ tokens = self._extract_tokens(text)
275
+ gray_entropy_delta = 0.75
276
+ gray_min_complexity = 0.60
277
+
278
+ for token in tokens:
279
+ entropy = self._shannon_entropy(token)
280
+ for whitelist_pattern in self.ENTROPY_WHITELIST_PATTERNS:
281
+ if whitelist_pattern.search(token):
282
+ entropy = entropy / 2.0
283
+ break
284
+
285
+ score_complexite = self._score_complexite(token)
286
+ rv = self._ratio_voyelles(token)
287
+
288
+ gray_structural = (
289
+ entropy > self._threshold - gray_entropy_delta
290
+ and entropy <= self._threshold
291
+ and len(token) >= self._min_length
292
+ and score_complexite >= gray_min_complexity
293
+ )
294
+
295
+ score_final = 0.0
296
+ reason = "entropie"
297
+
298
+ if entropy <= self._threshold:
299
+ if gray_structural:
300
+ score_final = 0.75
301
+ reason = "gray_structural"
302
+ else:
303
+ score_entropie = min(
304
+ (entropy - self._threshold) / (6.0 - self._threshold), 1.0
305
+ )
306
+ score_entropie = max(score_entropie, 0.0)
307
+ if rv < 0.10:
308
+ score_final = min(score_entropie * 1.20, 1.0)
309
+ elif rv > 0.35:
310
+ score_final = score_entropie * 0.60
311
+ else:
312
+ score_final = score_entropie
313
+
314
+ score_combine = max(
315
+ score_final, score_complexite, (score_final + score_complexite) / 2
316
+ )
317
+ score_final = min(score_combine, 1.0)
318
+
319
+ if (
320
+ entropy > self._threshold
321
+ and score_complexite >= 0.55
322
+ and len(token) >= self._min_length
323
+ ):
324
+ score_final = max(score_final, 0.90)
325
+
326
+ if score_final > 0:
327
+ candidates.append({
328
+ "matched": token,
329
+ "score": score_final,
330
+ "reason": reason,
331
+ "entropy": round(entropy, 2),
332
+ "vowels": round(rv, 2),
333
+ "complexity": round(score_complexite, 2)
334
+ })
335
+
336
+ return candidates