MUFASA25 commited on
Commit
f46002b
·
verified ·
1 Parent(s): bd554e8

first base model

Browse files
Files changed (1) hide show
  1. app.py +174 -55
app.py CHANGED
@@ -1,64 +1,183 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import os
5
 
6
+ # Model configuration
7
+ MODEL_NAME = "cybersectony/phishing-email-detection-distilbert_v2.4.1"
 
 
8
 
9
+ # Global variables for model and tokenizer
10
+ model = None
11
+ tokenizer = None
12
 
13
+ def load_model():
14
+ """Load model and tokenizer once at startup"""
15
+ global model, tokenizer
16
+ try:
17
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
18
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
19
+ model.eval() # Set to evaluation mode
20
+ return True
21
+ except Exception as e:
22
+ print(f"Error loading model: {e}")
23
+ return False
24
 
25
+ def predict_phishing(text):
26
+ """
27
+ Predict if email/URL is phishing or legitimate
28
+ """
29
+ global model, tokenizer
30
+
31
+ if not text.strip():
32
+ return "Please enter some text to analyze", {}, ""
33
+
34
+ try:
35
+ # Tokenize input
36
+ inputs = tokenizer(
37
+ text,
38
+ return_tensors="pt",
39
+ truncation=True,
40
+ max_length=512,
41
+ padding=True
42
+ )
43
+
44
+ # Get prediction
45
+ with torch.no_grad():
46
+ outputs = model(**inputs)
47
+ predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
48
+
49
+ # Get probabilities
50
+ probs = predictions[0].tolist()
51
+
52
+ # Label mapping
53
+ labels = {
54
+ "Legitimate Email": probs[0],
55
+ "Phishing URL": probs[1],
56
+ "Legitimate URL": probs[2],
57
+ "Phishing Email": probs[3] if len(probs) > 3 else 0
58
+ }
59
+
60
+ # Find highest probability
61
+ max_label = max(labels.items(), key=lambda x: x[1])
62
+ prediction = max_label[0]
63
+ confidence = max_label[1]
64
+
65
+ # Create confidence bar data
66
+ confidence_data = {label: f"{prob:.1%}" for label, prob in labels.items()}
67
+
68
+ # Risk assessment
69
+ if "Phishing" in prediction:
70
+ risk_level = "🚨 HIGH RISK - Potential Phishing Detected"
71
+ risk_color = "red"
72
+ else:
73
+ risk_level = "✅ LOW RISK - Appears Legitimate"
74
+ risk_color = "green"
75
+
76
+ # Format result
77
+ result = f"""
78
+ ### {risk_level}
79
+ **Primary Classification:** {prediction}
80
+ **Confidence:** {confidence:.1%}
81
+ """
82
+
83
+ return result, confidence_data, risk_color
84
+
85
+ except Exception as e:
86
+ return f"Error during prediction: {str(e)}", {}, "orange"
87
 
88
+ # Load model at startup
89
+ print("Loading model...")
90
+ model_loaded = load_model()
91
+ if not model_loaded:
92
+ print("Failed to load model!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ # Create Gradio interface
95
+ with gr.Blocks(
96
+ theme=gr.themes.Soft(),
97
+ title="Phishing Email & URL Detective",
98
+ css="""
99
+ .risk-high { color: #dc2626 !important; font-weight: bold; }
100
+ .risk-low { color: #16a34a !important; font-weight: bold; }
101
+ .main-container { max-width: 800px; margin: 0 auto; }
102
+ """
103
+ ) as demo:
104
+
105
+ gr.Markdown("""
106
+ # 🛡️ Phishing Detection System
107
+ **Instantly detect phishing emails and malicious URLs using AI**
108
+
109
+ Powered by DistilBERT • 99.58% Accuracy • Real-time Analysis
110
+ """)
111
+
112
+ with gr.Row():
113
+ with gr.Column(scale=2):
114
+ input_text = gr.Textbox(
115
+ label="📧 Email Content or URL",
116
+ placeholder="Paste suspicious email content or URL here...",
117
+ lines=8,
118
+ max_lines=15
119
+ )
120
+
121
+ analyze_btn = gr.Button(
122
+ "🔍 Analyze for Phishing",
123
+ variant="primary",
124
+ size="lg"
125
+ )
126
+
127
+ with gr.Column(scale=1):
128
+ result_output = gr.Markdown(label="Analysis Result")
129
+
130
+ confidence_output = gr.Label(
131
+ label="Confidence Breakdown",
132
+ num_top_classes=4
133
+ )
134
+
135
+ # Example inputs
136
+ gr.Markdown("### 📋 Try These Examples:")
137
+
138
+ examples = [
139
+ ["Dear User, Your account will be suspended! Click here immediately: http://fake-bank-login.com/urgent"],
140
+ ["Hi Mufasa, Thanks for your email. The quarterly report is attached. Best regards, Simba"],
141
+ ["URGENT: Verify your PayPal account now or lose access: https://paypal-security-verify.suspicious.com"],
142
+ ["Meeting reminder: Project sync at 3 PM in conference room B. See you there!"]
143
+ ]
144
+
145
+ gr.Examples(
146
+ examples=examples,
147
+ inputs=input_text,
148
+ outputs=[result_output, confidence_output]
149
+ )
150
+
151
+ # Event handlers
152
+ analyze_btn.click(
153
+ fn=predict_phishing,
154
+ inputs=input_text,
155
+ outputs=[result_output, confidence_output, gr.State()]
156
+ )
157
+
158
+ input_text.submit(
159
+ fn=predict_phishing,
160
+ inputs=input_text,
161
+ outputs=[result_output, confidence_output, gr.State()]
162
+ )
163
+
164
+ gr.Markdown("""
165
+ ---
166
+ ### ℹ️ About This Tool and the team.
167
+ - **Model:** DistilBERT fine-tuned for phishing detection
168
+ - **Accuracy:** 99.58% on test dataset
169
+ - **Speed:** Real-time analysis
170
+ - **Privacy:** All processing happens locally, no data stored
171
+
172
+ **⚠️ Disclaimer:** This tool is for educational purposes (Assignemnt) only, we currently hold no rights and responsibility to this tool. So please Always verify suspicious content through official channels.
173
+ """)
174
 
175
+ # Launch configuration
176
  if __name__ == "__main__":
177
+ demo.launch(
178
+ share=False,
179
+ server_name="0.0.0.0",
180
+ server_port=7860,
181
+ show_error=True,
182
+ quiet=False
183
+ )