Titembaye commited on
Commit
0940697
·
verified ·
1 Parent(s): d2a4487

interface pro 1

Browse files
Files changed (1) hide show
  1. app.py +130 -199
app.py CHANGED
@@ -1,230 +1,161 @@
1
  """
2
- Application Gradio - Détecteur de Phishing
3
- Modèle: BERT fine-tuné avec adversarial training
 
 
4
  """
5
 
 
 
 
 
 
6
  import gradio as gr
7
  import torch
8
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
9
- import os
10
 
11
- # Configuration
12
- MODEL_PATH = "models"
13
  MAX_LENGTH = 256
14
- DEVICE = torch.device("cpu") # Force CPU pour Hugging Face Spaces gratuit
15
-
16
- print("="*60)
17
- print("Initialisation du Détecteur de Phishing")
18
- print("="*60)
19
-
20
- # Vérifier que le modèle existe
21
- if not os.path.exists(MODEL_PATH):
22
- raise FileNotFoundError(
23
- f"Modèle introuvable: {MODEL_PATH}\n"
24
- f" Assurez-vous que le dossier existe et contient les fichiers du modèle."
25
- )
26
-
27
- # Charger le tokenizer et le modèle
28
- print(f"Chargement du tokenizer depuis {MODEL_PATH}...")
29
- tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
30
-
31
- print(f"Chargement du modèle depuis {MODEL_PATH}...")
32
- # Charger en mode CPU avec optimisations mémoire
33
- model = AutoModelForSequenceClassification.from_pretrained(
34
- MODEL_PATH,
35
- torch_dtype=torch.float32, # Utiliser float32 pour compatibilité CPU
36
- low_cpu_mem_usage=True # Optimisation mémoire
37
- )
38
- model.to(DEVICE)
39
- model.eval()
 
 
 
 
 
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
- email_text,
62
  max_length=MAX_LENGTH,
63
- padding='max_length',
64
  truncation=True,
65
- return_tensors='pt'
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
- probabilities = torch.softmax(logits, dim=1)[0]
76
- predicted_class = torch.argmax(probabilities).item()
77
- confidence = probabilities[predicted_class].item()
78
-
79
- # Résultats
80
- label = "🚨Phishing Détecté" if predicted_class == 1 else "✅ Email Légitime"
81
-
82
- prob_dict = {
83
- "Légitime": float(probabilities[0]),
84
- "Phishing": float(probabilities[1])
85
- }
86
-
87
- # Analyse détaillée
88
- analysis = f"""
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
- # Exemples d'emails pour la démo
112
- examples = [
113
- ["""Dear valued customer,
114
-
115
- Your account has been suspended due to unusual activity.
116
- Please verify your identity immediately by clicking the link below:
117
-
118
- http://secure-verify-account.com/login
119
-
120
- You have 24 hours to verify or your account will be permanently closed.
121
-
122
- Best regards,
123
- Security Team"""],
124
-
125
- ["""Hi team,
126
-
127
- Just a reminder that our weekly meeting is scheduled for tomorrow at 2 PM in Conference Room B.
128
-
129
- Please bring your project updates.
130
-
131
- Thanks,
132
- John"""],
133
-
134
- ["""URGENT: You have won $1,000,000 in the international lottery!
135
-
136
- To claim your prize, send us your bank details and a processing fee of $500.
137
-
138
- Contact us immediately: winner@lottery-prize.com
139
-
140
- Congratulations!"""],
141
-
142
- ["""Hello,
143
-
144
- Your package delivery failed.
145
- Track your package here: https://trackpackage.com/xyz123
146
-
147
- Delivery company will retry tomorrow between 9 AM - 5 PM.
148
-
149
- Tracking ID: XYZ123456"""]
150
- ]
151
-
152
-
153
- # Interface Gradio
154
- with gr.Blocks(theme=gr.themes.Soft(), title="Détecteur de Phishing") as demo:
155
- gr.Markdown("""
156
- # Détecteur de Phishing par Intelligence Artificielle
157
-
158
- Cette application utilise un modèle **BERT fine-tuné avec adversarial training**
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", size="lg")
179
- clear_btn = gr.ClearButton([email_input], value="🗑️ Effacer")
180
-
 
 
181
  with gr.Column(scale=1):
182
- verdict_output = gr.Textbox(
183
- label="Verdict",
184
- interactive=False,
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
- analysis_output = gr.Markdown(label="📈 Analyse Détaillée")
195
-
196
- # Exemples
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
- fn=predict_phishing,
213
- inputs=email_input,
214
- outputs=[verdict_output, prob_output, analysis_output]
215
- )
216
 
 
 
 
 
 
217
 
218
  if __name__ == "__main__":
219
- print("\n" + "="*60)
220
- print("Lancement de l'application Gradio")
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)