File size: 14,379 Bytes
960046a e7d473b 79ba3d4 e7d473b 960046a e7d473b 960046a e7d473b 960046a e7d473b 960046a e7d473b 960046a e7d473b 960046a e7d473b 960046a e7d473b 960046a e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 960046a e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 79ba3d4 e7d473b 0940697 960046a e7d473b 960046a e7d473b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | """
PhiBERT Sentinel - Détecteur de Phishing par IA
Modèle: XLM-RoBERTa fine-tuné avec adversarial training
Interface professionnelle avec jauge de risque, historique et export.
"""
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import os
import io
from datetime import datetime
# ============================================================
# Configuration
# ============================================================
MODEL_PATH = "models"
MAX_LENGTH = 256
DEVICE = torch.device("cpu") # Force CPU pour Hugging Face Spaces gratuit
APP_NAME = "PhiBERT Sentinel"
print("=" * 60)
print(f"Initialisation de {APP_NAME}")
print("=" * 60)
if not os.path.exists(MODEL_PATH):
raise FileNotFoundError(
f"Modèle introuvable: {MODEL_PATH}\n"
f" Assurez-vous que le dossier existe et contient les fichiers du modèle."
)
print(f"Chargement du tokenizer depuis {MODEL_PATH}...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
print(f"Chargement du modèle depuis {MODEL_PATH}...")
model = AutoModelForSequenceClassification.from_pretrained(
MODEL_PATH,
torch_dtype=torch.float32,
low_cpu_mem_usage=True
)
model.to(DEVICE)
model.eval()
print("Modèle chargé avec succès!")
print(f"Device: {DEVICE}")
print("=" * 60 + "\n")
# ============================================================
# Thème & CSS personnalisés — style "Security Operations Center"
# ============================================================
THEME = gr.themes.Base(
primary_hue=gr.themes.colors.cyan,
secondary_hue=gr.themes.colors.slate,
neutral_hue=gr.themes.colors.slate,
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
).set(
body_background_fill="#0b0f19",
body_background_fill_dark="#0b0f19",
background_fill_primary="#131a2a",
background_fill_primary_dark="#131a2a",
background_fill_secondary="#0f1520",
background_fill_secondary_dark="#0f1520",
border_color_primary="#243046",
block_background_fill="#131a2a",
block_border_color="#243046",
block_label_text_color="#8fa3c7",
block_title_text_color="#e6edf7",
body_text_color="#dbe4f3",
body_text_color_subdued="#8fa3c7",
button_primary_background_fill="#06b6d4",
button_primary_background_fill_hover="#22d3ee",
button_primary_text_color="#001018",
button_secondary_background_fill="#1c2436",
button_secondary_text_color="#dbe4f3",
input_background_fill="#0f1520",
input_border_color="#2a3752",
)
CUSTOM_CSS = """
#app-header {
background: linear-gradient(135deg, #0e1830 0%, #0b0f19 100%);
border: 1px solid #243046;
border-radius: 14px;
padding: 22px 28px;
margin-bottom: 18px;
}
#app-header h1 {
font-size: 1.7rem;
font-weight: 700;
margin: 0;
color: #e6edf7;
letter-spacing: -0.02em;
}
#app-header .tagline {
color: #7fdcec;
font-size: 0.95rem;
font-weight: 500;
margin-top: 4px;
}
#app-header .badges span {
display: inline-block;
background: #0f2530;
color: #7fdcec;
border: 1px solid #1d4f5c;
border-radius: 999px;
padding: 3px 12px;
font-size: 0.75rem;
margin-right: 6px;
margin-top: 10px;
}
.gauge-wrap {
background: #0f1520;
border: 1px solid #243046;
border-radius: 12px;
padding: 18px 20px;
text-align: center;
}
.gauge-verdict {
font-size: 1.25rem;
font-weight: 700;
margin-bottom: 10px;
}
.gauge-bar-bg {
width: 100%;
height: 14px;
background: #1c2436;
border-radius: 999px;
overflow: hidden;
margin: 10px 0 6px 0;
}
.gauge-bar-fill {
height: 100%;
border-radius: 999px;
transition: width 0.4s ease;
}
.gauge-labels {
display: flex;
justify-content: space-between;
font-size: 0.75rem;
color: #8fa3c7;
}
.gauge-risklevel {
display: inline-block;
margin-top: 10px;
padding: 4px 14px;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 600;
}
footer {visibility: hidden}
"""
# ============================================================
# Fonctions utilitaires
# ============================================================
def risk_level(phishing_prob):
"""Retourne (label, couleur) selon le niveau de risque."""
if phishing_prob < 0.30:
return "Risque faible", "#22c55e"
elif phishing_prob < 0.70:
return "Risque modéré", "#f59e0b"
else:
return "Risque élevé", "#ef4444"
def build_gauge_html(label, confidence, phishing_prob):
risk_label, color = risk_level(phishing_prob)
pct = phishing_prob * 100
return f"""
<div class="gauge-wrap">
<div class="gauge-verdict" style="color:{color}">{label}</div>
<div class="gauge-bar-bg">
<div class="gauge-bar-fill" style="width:{pct:.1f}%; background:{color};"></div>
</div>
<div class="gauge-labels">
<span>0% (légitime)</span>
<span>100% (phishing)</span>
</div>
<div class="gauge-risklevel" style="background:{color}22; color:{color}; border:1px solid {color}55;">
{risk_label} · confiance {confidence*100:.1f}%
</div>
</div>
"""
def predict_phishing(email_text, history):
"""
Analyse un email et met à jour l'historique de session.
"""
if history is None:
history = []
if not email_text.strip():
empty_gauge = """<div class="gauge-wrap"><span style="color:#8fa3c7;">
En attente d'un email à analyser…</span></div>"""
return empty_gauge, "", history, history
inputs = tokenizer(
email_text,
max_length=MAX_LENGTH,
padding='max_length',
truncation=True,
return_tensors='pt'
)
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
probabilities = torch.softmax(logits, dim=1)[0]
predicted_class = torch.argmax(probabilities).item()
confidence = probabilities[predicted_class].item()
phishing_prob = float(probabilities[1])
label = "Phishing détecté" if predicted_class == 1 else "Email légitime"
risk_label, _ = risk_level(phishing_prob)
gauge_html = build_gauge_html(label, confidence, phishing_prob)
analysis = f"""
### Analyse détaillée
| Élément | Valeur |
|---|---|
| **Verdict** | {label} |
| **Niveau de risque** | {risk_label} |
| **Confiance du modèle** | {confidence * 100:.1f}% |
| **Probabilité légitime** | {probabilities[0] * 100:.2f}% |
| **Probabilité phishing** | {probabilities[1] * 100:.2f}% |
| **Modèle** | XLM-RoBERTa (adversarial training) |
| **Longueur du texte** | {len(email_text)} caractères |
| **Tokens** | {len(tokenizer.encode(email_text))} |
| **Horodatage** | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} |
Cette analyse est fournie à titre éducatif uniquement. En cas de doute sur un email réel,
contactez votre service informatique ou l'expéditeur présumé par un canal sécurisé.
"""
entry = {
"Horodatage": datetime.now().strftime('%H:%M:%S'),
"Verdict": label,
"Risque": risk_label,
"Confiance (%)": round(confidence * 100, 1),
"Aperçu email": (email_text[:60] + "…") if len(email_text) > 60 else email_text,
}
history = history + [entry]
return gauge_html, analysis, history, history
def history_to_table(history):
if not history:
return [["—", "—", "—", "—", "—"]]
return [
[h["Horodatage"], h["Verdict"], h["Risque"], h["Confiance (%)"], h["Aperçu email"]]
for h in reversed(history)
]
def clear_history():
return [], history_to_table([])
def export_report(email_text, analysis_markdown, history):
"""Génère un rapport texte téléchargeable de la dernière analyse."""
if not analysis_markdown.strip():
return None
report = io.StringIO()
report.write(f"{APP_NAME} — Rapport d'analyse\n")
report.write("=" * 50 + "\n\n")
report.write(f"Généré le : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
report.write("Email analysé :\n")
report.write("-" * 50 + "\n")
report.write(email_text.strip() + "\n\n")
report.write("Résultats :\n")
report.write("-" * 50 + "\n")
report.write(analysis_markdown.strip() + "\n")
filename = f"rapport_phibert_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
filepath = os.path.join("/tmp", filename)
with open(filepath, "w", encoding="utf-8") as f:
f.write(report.getvalue())
return filepath
# ============================================================
# Exemples
# ============================================================
examples = [
["""Dear valued customer,
Your account has been suspended due to unusual activity.
Please verify your identity immediately by clicking the link below:
http://secure-verify-account.com/login
You have 24 hours to verify or your account will be permanently closed.
Best regards,
Security Team"""],
["""Hi team,
Just a reminder that our weekly meeting is scheduled for tomorrow at 2 PM in Conference Room B.
Please bring your project updates.
Thanks,
John"""],
["""URGENT: You have won $1,000,000 in the international lottery!
To claim your prize, send us your bank details and a processing fee of $500.
Contact us immediately: winner@lottery-prize.com
Congratulations!"""],
["""Hello,
Your package delivery failed.
Track your package here: https://trackpackage.com/xyz123
Delivery company will retry tomorrow between 9 AM - 5 PM.
Tracking ID: XYZ123456"""]
]
# ============================================================
# Interface Gradio
# ============================================================
with gr.Blocks(theme=THEME, css=CUSTOM_CSS, title=APP_NAME) as demo:
history_state = gr.State([])
gr.HTML(f"""
<div id="app-header">
<h1>{APP_NAME}</h1>
<div class="tagline">Détection de phishing par intelligence artificielle — XLM-RoBERTa + adversarial training</div>
<div class="badges">
<span>Cross-lingue EN/FR</span>
<span>Robustesse adversariale</span>
<span>Inférence temps réel</span>
</div>
</div>
""")
with gr.Tabs():
# ---------------- Onglet Analyse ----------------
with gr.Tab("Analyse"):
with gr.Row():
with gr.Column(scale=3):
email_input = gr.Textbox(
label="Contenu de l'email",
placeholder="Collez ici le contenu de l'email à analyser…",
lines=12,
max_lines=25
)
with gr.Row():
analyze_btn = gr.Button("Analyser", variant="primary", size="lg")
clear_btn = gr.ClearButton([email_input], value="Effacer")
export_btn = gr.Button("Exporter le rapport", size="lg")
export_file = gr.File(label="Rapport généré", visible=True)
with gr.Column(scale=2):
gauge_output = gr.HTML(
value="""<div class="gauge-wrap"><span style="color:#8fa3c7;">
En attente d'un email à analyser…</span></div>"""
)
with gr.Row():
analysis_output = gr.Markdown()
gr.Markdown("### Exemples à tester")
gr.Examples(
examples=examples,
inputs=email_input,
label="Cliquez sur un exemple pour le tester"
)
# ---------------- Onglet Historique ----------------
with gr.Tab("Historique de session"):
gr.Markdown(
"Historique des analyses effectuées durant cette session "
"(réinitialisé à chaque rechargement de la page)."
)
history_table = gr.Dataframe(
headers=["Heure", "Verdict", "Risque", "Confiance (%)", "Aperçu email"],
value=[["—", "—", "—", "—", "—"]],
interactive=False,
wrap=True,
)
clear_history_btn = gr.Button("Vider l'historique")
# ---------------- Onglet À propos ----------------
with gr.Tab("À propos"):
gr.Markdown(f"""
### {APP_NAME}
Cette application utilise un modèle **XLM-RoBERTa fine-tuné avec adversarial training**
pour détecter les emails de phishing, avec un focus sur :
- **Robustesse** face aux attaques adversariales générées par IA
- **Généralisation cross-linguale** (anglais / français)
### Niveaux de risque
- **Risque faible** — probabilité de phishing < 30%
- **Risque modéré** — probabilité de phishing entre 30% et 70%
- **Risque élevé** — probabilité de phishing > 70%
---
**Avertissement** : cette application est fournie à des fins éducatives et de
recherche uniquement. Elle ne remplace pas les outils de sécurité professionnels
de votre organisation.
""")
# ---------------- Actions ----------------
analyze_btn.click(
fn=predict_phishing,
inputs=[email_input, history_state],
outputs=[gauge_output, analysis_output, history_state, history_state]
).then(
fn=history_to_table,
inputs=history_state,
outputs=history_table
)
export_btn.click(
fn=export_report,
inputs=[email_input, analysis_output, history_state],
outputs=export_file
)
clear_history_btn.click(
fn=clear_history,
outputs=[history_state, history_table]
)
if __name__ == "__main__":
print("\n" + "=" * 60)
print(f"Lancement de {APP_NAME}")
print("=" * 60)
print(f"Device: {DEVICE}")
print(f"Modèle: {MODEL_PATH}")
print("=" * 60 + "\n")
demo.launch(
show_error=True,
server_name="0.0.0.0",
server_port=7860
) |