Pant0x commited on
Commit
ecdfe0a
Β·
verified Β·
1 Parent(s): 91c1466

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -120
app.py CHANGED
@@ -1,125 +1,26 @@
1
  import gradio as gr
2
- import torch
3
- import torch.nn as nn
4
- import pickle
5
- import numpy as np
6
 
7
- # ---------------------------------------------------------
8
- # 1. Define the Neural Network Architecture
9
- # ---------------------------------------------------------
10
- # Since your file is an OrderedDict, we must define the class
11
- # that matches the layers inside it.
12
- # I am assuming a standard 5-input architecture based on your feature extractor.
13
- class PhishingNet(nn.Module):
14
- def __init__(self, input_size=5, hidden_size=10, output_size=2):
15
- super(PhishingNet, self).__init__()
16
- self.fc1 = nn.Linear(input_size, hidden_size)
17
- self.relu = nn.ReLU()
18
- self.fc2 = nn.Linear(hidden_size, output_size)
19
-
20
- def forward(self, x):
21
- out = self.fc1(x)
22
- out = self.relu(out)
23
- out = self.fc2(out)
24
- return out
25
-
26
- # ---------------------------------------------------------
27
- # 2. Load Resources (Model + Scaler)
28
- # ---------------------------------------------------------
29
- MODEL_PATH = "models/phishing_rf_model.pt"
30
- SCALER_PATH = "models/scaler.pkl"
31
-
32
- model = None
33
- scaler = None
34
- load_status = ""
35
-
36
- try:
37
- # --- Load Scaler ---
38
- with open(SCALER_PATH, "rb") as f:
39
- scaler = pickle.load(f)
40
- load_status += "βœ… Scaler loaded.\n"
41
-
42
- # --- Load Model Weights ---
43
- # We load the weights (OrderedDict)
44
- state_dict = torch.load(MODEL_PATH, map_location=torch.device('cpu'))
45
 
46
- # We create the structure.
47
- # NOTE: If this crashes with "Shape Mismatch", we will catch it below.
48
- model = PhishingNet()
49
- model.load_state_dict(state_dict)
50
- model.eval() # Set to evaluation mode
51
- load_status += "βœ… Model weights loaded into Neural Net.\n"
52
-
53
- except Exception as e:
54
- load_status += f"❌ LOAD ERROR: {str(e)}\n"
55
- print(load_status)
56
-
57
- # ---------------------------------------------------------
58
- # 3. Feature Extraction (Must match your Scaler!)
59
- # ---------------------------------------------------------
60
- def extract_features(url: str) -> np.ndarray:
61
- length = len(url)
62
- dots = url.count('.')
63
- hyphens = url.count('-')
64
- digits = sum(c.isdigit() for c in url)
65
- at_sign = url.count('@')
66
 
67
- # Return shape [1, 5]
68
- return np.array([[length, dots, hyphens, digits, at_sign]], dtype=float)
69
-
70
- # ---------------------------------------------------------
71
- # 4. Prediction Logic
72
- # ---------------------------------------------------------
73
- def predict_phishing(url):
74
- # Check if things loaded correctly
75
- if model is None or scaler is None:
76
- return {"Error": 0}, f"System not ready.\n{load_status}"
77
-
78
- if not url:
79
- return None, "Please enter a URL."
80
-
81
  try:
82
- # 1. Extract
83
- features = extract_features(url)
84
-
85
- # 2. Scale (Using your scaler)
86
- features_scaled = scaler.transform(features)
87
-
88
- # 3. Convert to Torch Tensor
89
- features_tensor = torch.tensor(features_scaled, dtype=torch.float32)
90
-
91
- # 4. Predict
92
- with torch.no_grad():
93
- logits = model(features_tensor)
94
- probs = torch.nn.functional.softmax(logits, dim=1)
95
-
96
- # Assume Index 0 = Safe, Index 1 = Phishing
97
- safe_conf = float(probs[0][0])
98
- phish_conf = float(probs[0][1])
99
-
100
- return {"βœ… Safe": safe_conf, "🚨 Phishing": phish_conf}, "Success"
101
-
102
- except Exception as e:
103
- return {"Error": 0}, f"Prediction Failed: {str(e)}"
104
-
105
- # ---------------------------------------------------------
106
- # 5. UI Setup
107
- # ---------------------------------------------------------
108
- with gr.Blocks(theme=gr.themes.Soft()) as iface:
109
- gr.Markdown("# πŸ›‘οΈ PhishScope (Custom Model)")
110
-
111
- with gr.Row():
112
- url_input = gr.Textbox(label="URL to Check", placeholder="https://example.com")
113
- submit_btn = gr.Button("Analyze", variant="primary")
114
-
115
- with gr.Row():
116
- label_output = gr.Label(label="Result")
117
- debug_output = gr.Textbox(label="System Status", value=load_status, lines=4)
118
-
119
- submit_btn.click(
120
- fn=predict_phishing,
121
- inputs=url_input,
122
- outputs=[label_output, debug_output]
123
- )
124
-
125
- iface.launch()
 
1
  import gradio as gr
2
+ import os
 
 
 
3
 
4
+ def inspect_file():
5
+ path = "models/scaler.pkl"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ if not os.path.exists(path):
8
+ return f"❌ File not found at: {path}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Read the file as plain text to see if it's an LFS pointer
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  try:
12
+ with open(path, "r", encoding="utf-8") as f:
13
+ content = f.read(200) # Read first 200 characters
14
+ return f"⚠️ FILE CONTENT (Read as Text):\n\n{content}\n\n(If you see 'version https://git-lfs...', this is a FAKE file.)"
15
+ except UnicodeDecodeError:
16
+ # If it fails to read as text, that's actually GOOD news (it might be binary)
17
+ file_size = os.path.getsize(path)
18
+ return f"βœ… Good News! The file is binary (not text). Size: {file_size} bytes."
19
+
20
+ with gr.Blocks() as demo:
21
+ gr.Markdown("# File Inspector")
22
+ btn = gr.Button("Check Scaler File")
23
+ out = gr.Textbox(label="Result")
24
+ btn.click(fn=inspect_file, inputs=None, outputs=out)
25
+
26
+ demo.launch()