"""
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"""
{label}
0% (légitime)
100% (phishing)
{risk_label} · confiance {confidence*100:.1f}%
"""
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 = """
En attente d'un email à analyser…
"""
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"""
""")
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="""
En attente d'un email à analyser…
"""
)
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
)