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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/inference.py
|
| 2 |
+
"""
|
| 3 |
+
ClearDDI β moteur d'infΓ©rence
|
| 4 |
+
Charge les artefacts rΓ©els du pipeline PolypharmaSafe (XGBoost binaire + multiclasse,
|
| 5 |
+
SHAP, mappings nom -> DrugBank ID -> SMILES) et expose les fonctions utilisΓ©es par l'API.
|
| 6 |
+
|
| 7 |
+
Prototype acadΓ©mique d'aide Γ la dΓ©cision β non destinΓ© Γ un usage clinique rΓ©el.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import pickle
|
| 14 |
+
import re
|
| 15 |
+
import difflib
|
| 16 |
+
import warnings
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from functools import lru_cache
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import joblib
|
| 22 |
+
import shap
|
| 23 |
+
from rdkit import Chem
|
| 24 |
+
from rdkit.Chem import rdFingerprintGenerator, AllChem, Draw
|
| 25 |
+
|
| 26 |
+
warnings.filterwarnings("ignore")
|
| 27 |
+
|
| 28 |
+
# ============ CHEMIN DES ARTEFACTS ============
|
| 29 |
+
# Correction : les artefacts sont dans le dossier parent "artifacts"
|
| 30 |
+
# Le fichier inference.py est dans backend/
|
| 31 |
+
ARTIFACTS_DIR = Path(__file__).resolve().parent.parent / "artifacts"
|
| 32 |
+
|
| 33 |
+
print(f"π Chargement des artefacts depuis : {ARTIFACTS_DIR}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
+
# Chargement des artefacts (une seule fois, au dΓ©marrage du serveur)
|
| 38 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
|
| 40 |
+
def _load_artifacts():
|
| 41 |
+
with open(ARTIFACTS_DIR / "name_to_id.pkl", "rb") as f:
|
| 42 |
+
name_to_id = pickle.load(f)
|
| 43 |
+
with open(ARTIFACTS_DIR / "id_to_smiles.pkl", "rb") as f:
|
| 44 |
+
id_to_smiles = pickle.load(f)
|
| 45 |
+
with open(ARTIFACTS_DIR / "inference_config.json", encoding="utf-8") as f:
|
| 46 |
+
config = json.load(f)
|
| 47 |
+
with open(ARTIFACTS_DIR / "metrics.json", encoding="utf-8") as f:
|
| 48 |
+
metrics = json.load(f)
|
| 49 |
+
|
| 50 |
+
binary_model = joblib.load(ARTIFACTS_DIR / "ddi_binary_model.joblib")
|
| 51 |
+
multi_model = joblib.load(ARTIFACTS_DIR / "ddi_multiclass_model.joblib")
|
| 52 |
+
label_encoder = joblib.load(ARTIFACTS_DIR / "ddi_multiclass_label_encoder.joblib")
|
| 53 |
+
|
| 54 |
+
print("β
Artefacts chargés avec succès")
|
| 55 |
+
print(f" - Modèle binaire : {type(binary_model).__name__}")
|
| 56 |
+
print(f" - Modèle multi : {type(multi_model).__name__}")
|
| 57 |
+
print(f" - FP_BITS : {config.get('fp_bits', 2048)}")
|
| 58 |
+
|
| 59 |
+
return {
|
| 60 |
+
"name_to_id": name_to_id,
|
| 61 |
+
"id_to_smiles": id_to_smiles,
|
| 62 |
+
"config": config,
|
| 63 |
+
"metrics": metrics,
|
| 64 |
+
"binary_model": binary_model,
|
| 65 |
+
"multi_model": multi_model,
|
| 66 |
+
"label_encoder": label_encoder,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
_A = _load_artifacts()
|
| 71 |
+
NAME_TO_ID: dict[str, str] = _A["name_to_id"]
|
| 72 |
+
ID_TO_SMILES: dict[str, str] = _A["id_to_smiles"]
|
| 73 |
+
CONFIG: dict = _A["config"]
|
| 74 |
+
METRICS: dict = _A["metrics"]
|
| 75 |
+
BINARY_MODEL = _A["binary_model"]
|
| 76 |
+
MULTI_MODEL = _A["multi_model"]
|
| 77 |
+
LABEL_ENCODER = _A["label_encoder"]
|
| 78 |
+
|
| 79 |
+
FP_RADIUS = CONFIG["fp_radius"]
|
| 80 |
+
FP_BITS = CONFIG["fp_bits"]
|
| 81 |
+
DECISION_THRESHOLD = CONFIG.get("decision_threshold", 0.5)
|
| 82 |
+
|
| 83 |
+
_MFPGEN = rdFingerprintGenerator.GetMorganGenerator(radius=FP_RADIUS, fpSize=FP_BITS)
|
| 84 |
+
_SHAP_EXPLAINER = shap.TreeExplainer(BINARY_MODEL)
|
| 85 |
+
|
| 86 |
+
# Liste triΓ©e des noms connus, pour la recherche / les suggestions
|
| 87 |
+
_ALL_NAMES_SORTED = sorted(NAME_TO_ID.keys())
|
| 88 |
+
|
| 89 |
+
# Alias courants (franΓ§ais / noms commerciaux frΓ©quents) vers le nom DrugBank
|
| 90 |
+
_COMMON_ALIASES = {
|
| 91 |
+
"aspirine": "acetylsalicylic acid",
|
| 92 |
+
"aspirin": "acetylsalicylic acid",
|
| 93 |
+
"acide acetylsalicylique": "acetylsalicylic acid",
|
| 94 |
+
"warfarine": "warfarin",
|
| 95 |
+
"paracetamol": "acetaminophen",
|
| 96 |
+
"paracΓ©tamol": "acetaminophen",
|
| 97 |
+
"doliprane": "acetaminophen",
|
| 98 |
+
"tylenol": "acetaminophen",
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 103 |
+
# Connaissance mΓ©tier additionnelle
|
| 104 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 105 |
+
|
| 106 |
+
CLINICAL_TYPE_INFO = {
|
| 107 |
+
"HΓ©morragique": {
|
| 108 |
+
"label": "Risque hΓ©morragique",
|
| 109 |
+
"description": "Effet additif ou synergique sur l'hΓ©mostase, augmentant le risque de saignement.",
|
| 110 |
+
"side_effects": [
|
| 111 |
+
"Risque hΓ©morragique accru",
|
| 112 |
+
"Ecchymoses, saignements de nez",
|
| 113 |
+
"Hémorragie digestive (cas sévères)",
|
| 114 |
+
"Allongement du temps de coagulation",
|
| 115 |
+
],
|
| 116 |
+
},
|
| 117 |
+
"Cardiaque": {
|
| 118 |
+
"label": "Risque cardiaque (rythme)",
|
| 119 |
+
"description": "Effet potentiel sur la conduction cardiaque ou le rythme (allongement du QTc, arythmies).",
|
| 120 |
+
"side_effects": [
|
| 121 |
+
"Allongement de l'intervalle QTc",
|
| 122 |
+
"Risque de troubles du rythme (tachycardie, bradycardie)",
|
| 123 |
+
"Palpitations",
|
| 124 |
+
],
|
| 125 |
+
},
|
| 126 |
+
"Cardiovasculaire": {
|
| 127 |
+
"label": "Risque cardiovasculaire (tension)",
|
| 128 |
+
"description": "Interaction affectant la pression artΓ©rielle ou la fonction cardiovasculaire globale.",
|
| 129 |
+
"side_effects": [
|
| 130 |
+
"Hypotension ou hypertension",
|
| 131 |
+
"Γtourdissements posturaux",
|
| 132 |
+
"Modification de la frΓ©quence cardiaque",
|
| 133 |
+
],
|
| 134 |
+
},
|
| 135 |
+
"RΓ©nal": {
|
| 136 |
+
"label": "Risque rΓ©nal",
|
| 137 |
+
"description": "Effet potentiellement nΓ©phrotoxique ou altΓ©rant la clairance rΓ©nale.",
|
| 138 |
+
"side_effects": [
|
| 139 |
+
"AltΓ©ration de la fonction rΓ©nale",
|
| 140 |
+
"RΓ©duction de l'Γ©limination des toxines",
|
| 141 |
+
"Risque accru chez l'insuffisant rΓ©nal",
|
| 142 |
+
],
|
| 143 |
+
},
|
| 144 |
+
"HΓ©patique": {
|
| 145 |
+
"label": "Risque hΓ©patique",
|
| 146 |
+
"description": "Effet potentiel sur le mΓ©tabolisme ou la fonction hΓ©patique.",
|
| 147 |
+
"side_effects": [
|
| 148 |
+
"ΓlΓ©vation des enzymes hΓ©patiques",
|
| 149 |
+
"Risque d'hΓ©patotoxicitΓ©",
|
| 150 |
+
],
|
| 151 |
+
},
|
| 152 |
+
"MΓ©tabolique (CYP)": {
|
| 153 |
+
"label": "Interaction mΓ©tabolique (CYP450)",
|
| 154 |
+
"description": "Inhibition ou induction probable d'une enzyme du cytochrome P450, modifiant les concentrations plasmatiques.",
|
| 155 |
+
"side_effects": [
|
| 156 |
+
"Augmentation ou diminution de la concentration plasmatique d'un des deux mΓ©dicaments",
|
| 157 |
+
"Risque de surdosage relatif ou de sous-dosage",
|
| 158 |
+
"Effets toxiques liΓ©s Γ l'accumulation",
|
| 159 |
+
],
|
| 160 |
+
},
|
| 161 |
+
"ExcrΓ©tion": {
|
| 162 |
+
"label": "Interaction sur l'excrΓ©tion",
|
| 163 |
+
"description": "Modification probable de la clairance ou de l'Γ©limination d'un des deux mΓ©dicaments.",
|
| 164 |
+
"side_effects": [
|
| 165 |
+
"Variation du taux sΓ©rique du mΓ©dicament",
|
| 166 |
+
"Risque d'accumulation ou d'Γ©limination accΓ©lΓ©rΓ©e",
|
| 167 |
+
],
|
| 168 |
+
},
|
| 169 |
+
"HΓ©matologique": {
|
| 170 |
+
"label": "Risque hΓ©matologique",
|
| 171 |
+
"description": "Effet potentiel sur les cellules sanguines ou le transport de l'oxygène.",
|
| 172 |
+
"side_effects": [
|
| 173 |
+
"Risque de mΓ©thΓ©moglobinΓ©mie",
|
| 174 |
+
"Anomalies de la numΓ©ration sanguine",
|
| 175 |
+
],
|
| 176 |
+
},
|
| 177 |
+
"SΓ©dation/SNC": {
|
| 178 |
+
"label": "SΓ©dation / dΓ©pression du SNC",
|
| 179 |
+
"description": "Effet dépresseur additif sur le système nerveux central.",
|
| 180 |
+
"side_effects": [
|
| 181 |
+
"Somnolence accrue",
|
| 182 |
+
"Risque de dépression respiratoire (cas sévères)",
|
| 183 |
+
"AltΓ©ration de la vigilance",
|
| 184 |
+
],
|
| 185 |
+
},
|
| 186 |
+
"EfficacitΓ©": {
|
| 187 |
+
"label": "Modification d'efficacitΓ© thΓ©rapeutique",
|
| 188 |
+
"description": "Risque de rΓ©duction ou de potentialisation de l'effet thΓ©rapeutique d'un des deux mΓ©dicaments.",
|
| 189 |
+
"side_effects": [
|
| 190 |
+
"Perte d'efficacitΓ© thΓ©rapeutique",
|
| 191 |
+
"Effet thΓ©rapeutique exagΓ©rΓ©",
|
| 192 |
+
],
|
| 193 |
+
},
|
| 194 |
+
"Pharmacovigilance (TWOSIDES)": {
|
| 195 |
+
"label": "Signal de pharmacovigilance",
|
| 196 |
+
"description": "Association identifiΓ©e par signal statistique de pharmacovigilance (base TWOSIDES), sans mΓ©canisme unique Γ©tabli.",
|
| 197 |
+
"side_effects": [
|
| 198 |
+
"Profil d'effets indΓ©sirables non spΓ©cifique",
|
| 199 |
+
"Surveillance clinique recommandΓ©e",
|
| 200 |
+
],
|
| 201 |
+
},
|
| 202 |
+
"Autre": {
|
| 203 |
+
"label": "MΓ©canisme non catΓ©gorisΓ©",
|
| 204 |
+
"description": "Interaction dΓ©tectΓ©e sans correspondance claire avec les catΓ©gories cliniques principales.",
|
| 205 |
+
"side_effects": [
|
| 206 |
+
"MΓ©canisme Γ investiguer au cas par cas",
|
| 207 |
+
],
|
| 208 |
+
},
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 213 |
+
# Recherche de mΓ©dicament par nom
|
| 214 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 215 |
+
|
| 216 |
+
def normalize_name(name: str) -> str:
|
| 217 |
+
return re.sub(r"\s+", " ", name.strip().lower())
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def find_drug(name: str) -> dict | None:
|
| 221 |
+
"""Cherche un mΓ©dicament par nom (insensible Γ la casse). Retourne None si absent."""
|
| 222 |
+
key = normalize_name(name)
|
| 223 |
+
drug_id = NAME_TO_ID.get(key)
|
| 224 |
+
if drug_id is None:
|
| 225 |
+
alias = _COMMON_ALIASES.get(key)
|
| 226 |
+
if alias:
|
| 227 |
+
drug_id = NAME_TO_ID.get(alias)
|
| 228 |
+
key = alias
|
| 229 |
+
if drug_id is None:
|
| 230 |
+
return None
|
| 231 |
+
return {
|
| 232 |
+
"query": name,
|
| 233 |
+
"matched_name": key,
|
| 234 |
+
"drugbank_id": drug_id,
|
| 235 |
+
"smiles": ID_TO_SMILES[drug_id],
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def suggest_names(name: str, n: int = 5) -> list[str]:
|
| 240 |
+
"""Suggestions de noms proches (utilisΓ©es uniquement dans le message d'erreur)."""
|
| 241 |
+
key = normalize_name(name)
|
| 242 |
+
matches = difflib.get_close_matches(key, _ALL_NAMES_SORTED, n=n, cutoff=0.6)
|
| 243 |
+
if not matches:
|
| 244 |
+
matches = [n2 for n2 in _ALL_NAMES_SORTED if key in n2][:n]
|
| 245 |
+
return matches
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 249 |
+
# Featurisation
|
| 250 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 251 |
+
|
| 252 |
+
@lru_cache(maxsize=4096)
|
| 253 |
+
def _get_fp(smiles: str) -> np.ndarray:
|
| 254 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 255 |
+
if mol is None:
|
| 256 |
+
raise ValueError(f"SMILES invalide : {smiles}")
|
| 257 |
+
return _MFPGEN.GetFingerprintAsNumPy(mol).astype(np.int16)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def pair_features(smi_a: str, smi_b: str) -> np.ndarray:
|
| 261 |
+
"""Génère les features pour une paire de SMILES.
|
| 262 |
+
Le modèle attend 4096 features (fusion symétrique : somme + différence absolue)."""
|
| 263 |
+
fa, fb = _get_fp(smi_a), _get_fp(smi_b)
|
| 264 |
+
return np.concatenate([fa + fb, np.abs(fa - fb)]).reshape(1, -1)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def bit_to_fragment(smiles: str, bit_idx: int) -> str | None:
|
| 268 |
+
mol = Chem.MolFromSmiles(str(smiles))
|
| 269 |
+
if mol is None:
|
| 270 |
+
return None
|
| 271 |
+
bit_info: dict = {}
|
| 272 |
+
AllChem.GetMorganFingerprintAsBitVect(mol, FP_RADIUS, nBits=FP_BITS, bitInfo=bit_info)
|
| 273 |
+
if bit_idx not in bit_info:
|
| 274 |
+
return None
|
| 275 |
+
atom_idx, rad = bit_info[bit_idx][0]
|
| 276 |
+
env = Chem.FindAtomEnvironmentOfRadiusN(mol, rad, atom_idx)
|
| 277 |
+
submol = Chem.PathToSubmol(mol, env, atomMap={})
|
| 278 |
+
frag_smiles = Chem.MolToSmiles(submol)
|
| 279 |
+
return frag_smiles if frag_smiles else None
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def molecule_svg(smiles: str, width: int = 280, height: int = 220) -> str:
|
| 283 |
+
"""Génère un SVG 2D de la molécule (pour affichage dans l'interface)."""
|
| 284 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 285 |
+
if mol is None:
|
| 286 |
+
return ""
|
| 287 |
+
from rdkit.Chem.Draw import rdMolDraw2D
|
| 288 |
+
|
| 289 |
+
drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
|
| 290 |
+
opts = drawer.drawOptions()
|
| 291 |
+
opts.clearBackground = False
|
| 292 |
+
rdMolDraw2D.PrepareAndDrawMolecule(drawer, mol)
|
| 293 |
+
drawer.FinishDrawing()
|
| 294 |
+
svg = drawer.GetDrawingText()
|
| 295 |
+
return svg
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 299 |
+
# Risque & confiance
|
| 300 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 301 |
+
|
| 302 |
+
def risk_level(proba: float) -> str:
|
| 303 |
+
if proba < 0.35:
|
| 304 |
+
return "faible"
|
| 305 |
+
elif proba < 0.70:
|
| 306 |
+
return "modΓ©rΓ©"
|
| 307 |
+
return "Γ©levΓ©"
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def confidence_score(proba: float) -> float:
|
| 311 |
+
return float(abs(proba - 0.5) * 2)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 315 |
+
# Pipeline complet : prΓ©diction + explicabilitΓ©
|
| 316 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 317 |
+
|
| 318 |
+
def analyze_pair(name_a: str, name_b: str, top_k_fragments: int = 6) -> dict:
|
| 319 |
+
drug_a = find_drug(name_a)
|
| 320 |
+
if drug_a is None:
|
| 321 |
+
return {"error": "not_found", "which": "A", "query": name_a,
|
| 322 |
+
"suggestions": suggest_names(name_a)}
|
| 323 |
+
|
| 324 |
+
drug_b = find_drug(name_b)
|
| 325 |
+
if drug_b is None:
|
| 326 |
+
return {"error": "not_found", "which": "B", "query": name_b,
|
| 327 |
+
"suggestions": suggest_names(name_b)}
|
| 328 |
+
|
| 329 |
+
smi_a, smi_b = drug_a["smiles"], drug_b["smiles"]
|
| 330 |
+
|
| 331 |
+
mol_a, mol_b = Chem.MolFromSmiles(smi_a), Chem.MolFromSmiles(smi_b)
|
| 332 |
+
if mol_a is None or mol_b is None:
|
| 333 |
+
return {"error": "invalid_smiles"}
|
| 334 |
+
|
| 335 |
+
feat = pair_features(smi_a, smi_b)
|
| 336 |
+
|
| 337 |
+
# --- PrΓ©diction binaire ---
|
| 338 |
+
proba = float(BINARY_MODEL.predict_proba(feat)[0, 1])
|
| 339 |
+
level = risk_level(proba)
|
| 340 |
+
confidence = confidence_score(proba)
|
| 341 |
+
interaction_predicted = proba >= DECISION_THRESHOLD
|
| 342 |
+
|
| 343 |
+
# --- PrΓ©diction multiclasse (type clinique) ---
|
| 344 |
+
multi_probs = MULTI_MODEL.predict_proba(feat)[0]
|
| 345 |
+
order = np.argsort(multi_probs)[::-1]
|
| 346 |
+
clinical_ranking = [
|
| 347 |
+
{"type": LABEL_ENCODER.classes_[i], "probability": float(multi_probs[i])}
|
| 348 |
+
for i in order
|
| 349 |
+
]
|
| 350 |
+
top_clinical_type = clinical_ranking[0]["type"]
|
| 351 |
+
clinical_info = CLINICAL_TYPE_INFO.get(top_clinical_type, {
|
| 352 |
+
"label": top_clinical_type, "description": "", "side_effects": []
|
| 353 |
+
})
|
| 354 |
+
|
| 355 |
+
# --- SHAP : fragments responsables ---
|
| 356 |
+
shap_values = _SHAP_EXPLAINER.shap_values(feat)[0]
|
| 357 |
+
top_bits = np.argsort(np.abs(shap_values))[::-1][:top_k_fragments]
|
| 358 |
+
|
| 359 |
+
fragments = []
|
| 360 |
+
for bit in top_bits:
|
| 361 |
+
local_bit = int(bit % FP_BITS)
|
| 362 |
+
frag_a = bit_to_fragment(smi_a, local_bit)
|
| 363 |
+
frag_b = bit_to_fragment(smi_b, local_bit)
|
| 364 |
+
frag = frag_a or frag_b or None
|
| 365 |
+
source_drug = "A" if frag_a else ("B" if frag_b else None)
|
| 366 |
+
fragments.append({
|
| 367 |
+
"bit": local_bit,
|
| 368 |
+
"shap_value": float(shap_values[bit]),
|
| 369 |
+
"direction": "augmente le risque" if shap_values[bit] > 0 else "rΓ©duit le risque",
|
| 370 |
+
"fragment_smiles": frag,
|
| 371 |
+
"source_drug": source_drug,
|
| 372 |
+
})
|
| 373 |
+
|
| 374 |
+
reasons = build_reasons(fragments, clinical_info, proba)
|
| 375 |
+
|
| 376 |
+
return {
|
| 377 |
+
"error": None,
|
| 378 |
+
"drug_a": {"name": name_a.strip(), "drugbank_id": drug_a["drugbank_id"], "smiles": smi_a},
|
| 379 |
+
"drug_b": {"name": name_b.strip(), "drugbank_id": drug_b["drugbank_id"], "smiles": smi_b},
|
| 380 |
+
"prediction": {
|
| 381 |
+
"probability": proba,
|
| 382 |
+
"interaction_predicted": bool(interaction_predicted),
|
| 383 |
+
"risk_level": level,
|
| 384 |
+
"confidence": confidence,
|
| 385 |
+
"decision_threshold": DECISION_THRESHOLD,
|
| 386 |
+
},
|
| 387 |
+
"clinical_type": {
|
| 388 |
+
"top": top_clinical_type,
|
| 389 |
+
"label": clinical_info["label"],
|
| 390 |
+
"description": clinical_info["description"],
|
| 391 |
+
"ranking": clinical_ranking[:5],
|
| 392 |
+
},
|
| 393 |
+
"side_effects": clinical_info["side_effects"],
|
| 394 |
+
"fragments": fragments,
|
| 395 |
+
"reasons": reasons,
|
| 396 |
+
"model_metrics": {
|
| 397 |
+
"cold_start_auc": METRICS.get("cold_start", {}).get("auc"),
|
| 398 |
+
"warm_start_auc": METRICS.get("warm_start", {}).get("auc"),
|
| 399 |
+
},
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def build_reasons(fragments: list[dict], clinical_info: dict, proba: float) -> list[dict]:
|
| 404 |
+
reasons = []
|
| 405 |
+
|
| 406 |
+
positive_frags = [f for f in fragments if f["shap_value"] > 0 and f["fragment_smiles"]]
|
| 407 |
+
if positive_frags:
|
| 408 |
+
reasons.append({
|
| 409 |
+
"title": "Sous-structures molΓ©culaires partagΓ©es",
|
| 410 |
+
"detail": (
|
| 411 |
+
f"{len(positive_frags)} fragment(s) commun(s) ou similaires identifiΓ©s par SHAP "
|
| 412 |
+
f"contribuent positivement au score de risque."
|
| 413 |
+
),
|
| 414 |
+
})
|
| 415 |
+
|
| 416 |
+
if clinical_info.get("description"):
|
| 417 |
+
reasons.append({
|
| 418 |
+
"title": clinical_info["label"],
|
| 419 |
+
"detail": clinical_info["description"],
|
| 420 |
+
})
|
| 421 |
+
|
| 422 |
+
if proba >= 0.70:
|
| 423 |
+
reasons.append({
|
| 424 |
+
"title": "Score de probabilitΓ© Γ©levΓ©",
|
| 425 |
+
"detail": "La probabilitΓ© prΓ©dite dΓ©passe largement le seuil de dΓ©cision.",
|
| 426 |
+
})
|
| 427 |
+
elif proba < 0.35:
|
| 428 |
+
reasons.append({
|
| 429 |
+
"title": "Score de probabilitΓ© faible",
|
| 430 |
+
"detail": "Le modèle ne détecte pas de similarité significative avec des paires d'interaction connues.",
|
| 431 |
+
})
|
| 432 |
+
|
| 433 |
+
return reasons
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def list_sample_names(n: int = 12) -> list[str]:
|
| 437 |
+
preferred = [
|
| 438 |
+
"acetylsalicylic acid", "warfarin", "simvastatin", "clarithromycin",
|
| 439 |
+
"furosemide", "digoxin", "fluoxetine", "omeprazole",
|
| 440 |
+
]
|
| 441 |
+
found = [p for p in preferred if p in NAME_TO_ID]
|
| 442 |
+
return found[:n]
|