interface pro 1
Browse files
app.py
CHANGED
|
@@ -1,230 +1,161 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import gradio as gr
|
| 7 |
import torch
|
| 8 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 9 |
-
import os
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
MAX_LENGTH = 256
|
| 14 |
-
DEVICE = torch.device("cpu")
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
print("
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
#
|
| 33 |
-
model =
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
print(f"Modèle chargé avec succès!")
|
| 42 |
-
print(f"Device: {DEVICE}")
|
| 43 |
-
print("="*60 + "\n")
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def predict_phishing(email_text):
|
| 47 |
-
"""
|
| 48 |
-
Prédit si un email est du phishing ou légitime
|
| 49 |
-
|
| 50 |
-
Args:
|
| 51 |
-
email_text (str): Texte de l'email à analyser
|
| 52 |
-
|
| 53 |
-
Returns:
|
| 54 |
-
tuple: (verdict, probabilités, analyse détaillée)
|
| 55 |
-
"""
|
| 56 |
-
if not email_text.strip():
|
| 57 |
-
return "Veuillez entrer un email", {}, ""
|
| 58 |
-
|
| 59 |
-
# Tokenization
|
| 60 |
inputs = tokenizer(
|
| 61 |
-
|
| 62 |
max_length=MAX_LENGTH,
|
| 63 |
-
padding=
|
| 64 |
truncation=True,
|
| 65 |
-
return_tensors=
|
| 66 |
)
|
| 67 |
-
|
| 68 |
-
# Déplacer sur le bon device
|
| 69 |
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
| 70 |
-
|
| 71 |
-
# Prédiction
|
| 72 |
with torch.no_grad():
|
| 73 |
outputs = model(**inputs)
|
| 74 |
logits = outputs.logits
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
"Légitime
|
| 84 |
-
"Phishing
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
### Résultats de l'analyse
|
| 90 |
-
|
| 91 |
-
**Verdict:** {label}
|
| 92 |
-
**Confiance:** {confidence * 100:.1f}%
|
| 93 |
-
|
| 94 |
-
### Détails des probabilités
|
| 95 |
-
- **Légitime:** {probabilities[0] * 100:.2f}%
|
| 96 |
-
- **Phishing:** {probabilities[1] * 100:.2f}%
|
| 97 |
-
|
| 98 |
-
### Informations
|
| 99 |
-
- **Modèle:** BERT-base-uncased (adversarial training)
|
| 100 |
-
- **Longueur du texte:** {len(email_text)} caractères
|
| 101 |
-
- **Tokens:** {len(tokenizer.encode(email_text))} tokens
|
| 102 |
-
|
| 103 |
-
### Avertissement
|
| 104 |
-
Cette analyse est fournie à titre éducatif uniquement. En cas de doute sur un email réel,
|
| 105 |
-
contactez votre service informatique ou l'expéditeur présumé par un canal sécurisé.
|
| 106 |
-
"""
|
| 107 |
-
|
| 108 |
return label, prob_dict, analysis
|
| 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 |
-
pour détecter les emails de phishing.
|
| 160 |
-
|
| 161 |
-
**Axes d'évaluation:**
|
| 162 |
-
- Robustesse face aux attaques adversariales générées par IA
|
| 163 |
-
- Généralisation cross-linguale (EN/FR)
|
| 164 |
-
|
| 165 |
-
---
|
| 166 |
-
""")
|
| 167 |
|
| 168 |
with gr.Row():
|
| 169 |
with gr.Column(scale=2):
|
| 170 |
-
email_input = gr.Textbox(
|
| 171 |
-
label="📧 Collez votre email ici",
|
| 172 |
-
placeholder="Entrez le contenu de l'email à analyser...",
|
| 173 |
-
lines=10,
|
| 174 |
-
max_lines=20
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
with gr.Row():
|
| 178 |
-
analyze_btn = gr.Button("Analyser", variant="primary"
|
| 179 |
-
clear_btn = gr.ClearButton([email_input], value="
|
| 180 |
-
|
|
|
|
|
|
|
| 181 |
with gr.Column(scale=1):
|
| 182 |
-
verdict_output = gr.Textbox(
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
lines=2
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
prob_output = gr.Label(
|
| 189 |
-
label="Probabilités",
|
| 190 |
-
num_top_classes=2
|
| 191 |
-
)
|
| 192 |
|
|
|
|
| 193 |
with gr.Row():
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
gr.Markdown("### Exemples à tester")
|
| 198 |
-
gr.Examples(
|
| 199 |
-
examples=examples,
|
| 200 |
-
inputs=email_input,
|
| 201 |
-
label="Cliquez sur un exemple pour le tester"
|
| 202 |
-
)
|
| 203 |
-
|
| 204 |
-
# Footer
|
| 205 |
-
gr.Markdown("""
|
| 206 |
-
---
|
| 207 |
-
⚠️ **Disclaimer:** Cette application est fournie à des fins éducatives et de recherche uniquement.
|
| 208 |
-
""")
|
| 209 |
|
| 210 |
# Actions
|
| 211 |
-
analyze_btn.click(
|
| 212 |
-
|
| 213 |
-
inputs=email_input,
|
| 214 |
-
outputs=[verdict_output, prob_output, analysis_output]
|
| 215 |
-
)
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
if __name__ == "__main__":
|
| 219 |
-
print("
|
| 220 |
-
|
| 221 |
-
print("="*60)
|
| 222 |
-
print(f"Device: {DEVICE}")
|
| 223 |
-
print(f" Modèle: {MODEL_PATH}")
|
| 224 |
-
print("="*60 + "\n")
|
| 225 |
-
|
| 226 |
-
demo.launch(
|
| 227 |
-
show_error=True,
|
| 228 |
-
server_name="0.0.0.0", # Nécessaire pour Hugging Face Spaces
|
| 229 |
-
server_port=7860
|
| 230 |
-
)
|
|
|
|
| 1 |
"""
|
| 2 |
+
Gradio app améliorée — Détecteur de Phishing
|
| 3 |
+
- UI plus claire
|
| 4 |
+
- Téléversement CSV + export CSV de résultats
|
| 5 |
+
- Support: charger modèle local `models/` ou depuis HF Hub via env HF_MODEL
|
| 6 |
"""
|
| 7 |
|
| 8 |
+
import os
|
| 9 |
+
import io
|
| 10 |
+
import csv
|
| 11 |
+
import tempfile
|
| 12 |
+
import pandas as pd
|
| 13 |
import gradio as gr
|
| 14 |
import torch
|
| 15 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
|
|
|
| 16 |
|
| 17 |
+
# Config
|
| 18 |
+
MODEL_SOURCE = os.getenv("HF_MODEL", "models") # set HF_MODEL="username/model" in Space if needed
|
| 19 |
MAX_LENGTH = 256
|
| 20 |
+
DEVICE = torch.device("cpu")
|
| 21 |
+
|
| 22 |
+
def load_model(model_source: str):
|
| 23 |
+
print(f"Loading tokenizer & model from: {model_source}")
|
| 24 |
+
try:
|
| 25 |
+
tokenizer = AutoTokenizer.from_pretrained(model_source)
|
| 26 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 27 |
+
model_source,
|
| 28 |
+
torch_dtype=torch.float32,
|
| 29 |
+
low_cpu_mem_usage=True
|
| 30 |
+
)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
raise RuntimeError(f"Impossible de charger le modèle depuis '{model_source}': {e}")
|
| 33 |
+
model.to(DEVICE)
|
| 34 |
+
model.eval()
|
| 35 |
+
print("Model loaded.")
|
| 36 |
+
return tokenizer, model
|
| 37 |
+
|
| 38 |
+
# Lazy load (so HF Spaces can import file quickly)
|
| 39 |
+
tokenizer, model = None, None
|
| 40 |
+
def ensure_model():
|
| 41 |
+
global tokenizer, model
|
| 42 |
+
if tokenizer is None or model is None:
|
| 43 |
+
tokenizer, model = load_model(MODEL_SOURCE)
|
| 44 |
+
|
| 45 |
+
# Prediction helpers
|
| 46 |
+
def predict_phishing(email_text: str):
|
| 47 |
+
ensure_model()
|
| 48 |
+
text = (email_text or "").strip()
|
| 49 |
+
if not text:
|
| 50 |
+
return "Veuillez entrer un email", {"Légitime": 0.0, "Phishing": 0.0}, "Aucun texte fourni."
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
inputs = tokenizer(
|
| 53 |
+
text,
|
| 54 |
max_length=MAX_LENGTH,
|
| 55 |
+
padding="max_length",
|
| 56 |
truncation=True,
|
| 57 |
+
return_tensors="pt",
|
| 58 |
)
|
|
|
|
|
|
|
| 59 |
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
|
|
|
|
|
|
| 60 |
with torch.no_grad():
|
| 61 |
outputs = model(**inputs)
|
| 62 |
logits = outputs.logits
|
| 63 |
+
probs = torch.softmax(logits, dim=1)[0].cpu().tolist()
|
| 64 |
+
|
| 65 |
+
predicted = int(torch.argmax(torch.tensor(probs)).item())
|
| 66 |
+
label = "🚨 Phishing Détecté" if predicted == 1 else "✅ Email Légitime"
|
| 67 |
+
prob_dict = {"Légitime": float(probs[0]), "Phishing": float(probs[1])}
|
| 68 |
+
analysis = (
|
| 69 |
+
f"**Verdict:** {label}\n\n"
|
| 70 |
+
f"- **Confiance (max):** {max(probs)*100:.1f}%\n"
|
| 71 |
+
f"- **Légitime:** {prob_dict['Légitime']*100:.2f}%\n"
|
| 72 |
+
f"- **Phishing:** {prob_dict['Phishing']*100:.2f}%\n\n"
|
| 73 |
+
f"**Longueur du texte:** {len(text)} caractères\n"
|
| 74 |
+
f"**Tokens (approx):** {len(tokenizer.encode(text, add_special_tokens=False))}\n\n"
|
| 75 |
+
"⚠️ Résultat basé uniquement sur l'analyse textuelle. En cas de doute, vérifiez via d'autres canaux sécurisés."
|
| 76 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
return label, prob_dict, analysis
|
| 78 |
|
| 79 |
+
def predict_batch(uploaded_file):
|
| 80 |
+
ensure_model()
|
| 81 |
+
if uploaded_file is None:
|
| 82 |
+
return "Aucun fichier fourni.", pd.DataFrame(), None
|
| 83 |
+
|
| 84 |
+
# Read CSV into DataFrame (supports header or no header)
|
| 85 |
+
raw = uploaded_file.read().decode("utf-8")
|
| 86 |
+
stream = io.StringIO(raw)
|
| 87 |
+
try:
|
| 88 |
+
df = pd.read_csv(stream)
|
| 89 |
+
except Exception:
|
| 90 |
+
# fallback: try to read TSV or raw rows
|
| 91 |
+
stream.seek(0)
|
| 92 |
+
df = pd.read_csv(stream, sep=None, engine="python")
|
| 93 |
+
|
| 94 |
+
# choose text column
|
| 95 |
+
text_col = None
|
| 96 |
+
for c in df.columns:
|
| 97 |
+
if str(c).lower() in ("text", "email", "content", "body"):
|
| 98 |
+
text_col = c
|
| 99 |
+
break
|
| 100 |
+
if text_col is None:
|
| 101 |
+
text_col = df.columns[0]
|
| 102 |
+
|
| 103 |
+
results = []
|
| 104 |
+
for idx, row in df.iterrows():
|
| 105 |
+
text = str(row.get(text_col, "") or "")
|
| 106 |
+
label, probs, _ = predict_phishing(text)
|
| 107 |
+
results.append({
|
| 108 |
+
"index": idx,
|
| 109 |
+
"text": text if len(text) <= 200 else text[:197] + "...",
|
| 110 |
+
"verdict": label,
|
| 111 |
+
"prob_legitime": round(probs["Légitime"], 4),
|
| 112 |
+
"prob_phishing": round(probs["Phishing"], 4),
|
| 113 |
+
})
|
| 114 |
+
|
| 115 |
+
res_df = pd.DataFrame(results)
|
| 116 |
+
|
| 117 |
+
# Save CSV to tmp for download
|
| 118 |
+
tmpf = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
|
| 119 |
+
res_df.to_csv(tmpf.name, index=False, encoding="utf-8")
|
| 120 |
+
tmpf.close()
|
| 121 |
+
|
| 122 |
+
summary = f"Analysé {len(res_df)} entrées. Téléchargez le CSV pour voir tous les détails."
|
| 123 |
+
return summary, res_df, tmpf.name
|
| 124 |
+
|
| 125 |
+
# UI
|
| 126 |
+
with gr.Blocks(title="Détecteur de Phishing", theme=gr.themes.Soft()) as demo:
|
| 127 |
+
gr.Markdown("# 🛡️ Détecteur de Phishing (BERT)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
with gr.Row():
|
| 130 |
with gr.Column(scale=2):
|
| 131 |
+
email_input = gr.Textbox(label="📧 Collez votre email ici", lines=10, placeholder="Entrez le contenu de l'email...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
with gr.Row():
|
| 133 |
+
analyze_btn = gr.Button("🔍 Analyser", variant="primary")
|
| 134 |
+
clear_btn = gr.ClearButton([email_input], value="Effacer")
|
| 135 |
+
gr.Markdown("### Batch")
|
| 136 |
+
csv_upload = gr.File(file_types=[".csv"], label="Téléversez un CSV (colonne texte)")
|
| 137 |
+
batch_btn = gr.Button("Analyser le CSV")
|
| 138 |
with gr.Column(scale=1):
|
| 139 |
+
verdict_output = gr.Textbox(label="Verdict", interactive=False)
|
| 140 |
+
prob_output = gr.Label(label="Probabilités", num_top_classes=2)
|
| 141 |
+
analysis_output = gr.Markdown(label="Analyse détaillée")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
gr.Markdown("---")
|
| 144 |
with gr.Row():
|
| 145 |
+
batch_summary = gr.Textbox(label="Résumé batch", interactive=False)
|
| 146 |
+
batch_table = gr.Dataframe(headers=["index","text","verdict","prob_legitime","prob_phishing"], label="Résultats batch", interactive=False)
|
| 147 |
+
download_file = gr.File(label="Télécharger CSV de résultats")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
# Actions
|
| 150 |
+
analyze_btn.click(fn=predict_phishing, inputs=email_input, outputs=[verdict_output, prob_output, analysis_output])
|
| 151 |
+
batch_btn.click(fn=predict_batch, inputs=csv_upload, outputs=[batch_summary, batch_table, download_file])
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
+
# Footer / notes
|
| 154 |
+
gr.Markdown(
|
| 155 |
+
"⚠️ Cette application est fournie à des fins éducatives. Pour déployer depuis HF Hub, "
|
| 156 |
+
"définissez la variable d'environnement `HF_MODEL` (ex: username/model) dans les Settings du Space."
|
| 157 |
+
)
|
| 158 |
|
| 159 |
if __name__ == "__main__":
|
| 160 |
+
print("Starting Gradio app...")
|
| 161 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|