File size: 7,372 Bytes
1dea03f
9322097
6e62141
 
 
1dea03f
 
909902f
320abcb
1dea03f
3ba00ce
 
1dea03f
3ba00ce
 
 
 
 
 
 
7c4acd8
320abcb
 
3ba00ce
320abcb
3ba00ce
320abcb
6e62141
3ba00ce
320abcb
7c4acd8
320abcb
1dea03f
3ba00ce
1dea03f
 
3ba00ce
 
 
 
320abcb
1dea03f
320abcb
3ba00ce
 
 
1dea03f
3ba00ce
 
 
320abcb
3ba00ce
 
 
 
320abcb
3ba00ce
320abcb
3ba00ce
 
 
 
320abcb
1dea03f
3ba00ce
 
320abcb
3ba00ce
 
 
 
 
320abcb
3ba00ce
320abcb
 
1dea03f
3ba00ce
1dea03f
 
 
 
 
 
3ba00ce
 
320abcb
3ba00ce
 
 
 
320abcb
 
 
 
 
3ba00ce
 
 
 
 
 
 
320abcb
3ba00ce
320abcb
 
3ba00ce
 
320abcb
 
3ba00ce
 
7c4acd8
1dea03f
3ba00ce
320abcb
 
 
 
 
 
 
 
3ba00ce
 
6e62141
 
3ba00ce
 
320abcb
3ba00ce
320abcb
 
 
 
 
 
3ba00ce
 
 
320abcb
3ba00ce
 
320abcb
3ba00ce
 
 
 
320abcb
6e62141
 
 
3ba00ce
320abcb
3ba00ce
 
320abcb
 
 
 
 
3ba00ce
 
 
320abcb
3ba00ce
320abcb
 
3ba00ce
 
 
 
320abcb
6e62141
 
 
3ba00ce
 
320abcb
 
6e62141
3ba00ce
 
320abcb
 
3ba00ce
 
320abcb
 
 
3ba00ce
 
909902f
 
3ba00ce
 
320abcb
 
 
 
 
 
 
3ba00ce
 
 
 
 
320abcb
3ba00ce
 
 
320abcb
3ba00ce
 
 
7c4acd8
320abcb
3ba00ce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# app.py
import os
import logging
from flask import Flask, request, jsonify
from flask_cors import CORS
import joblib
import numpy as np

# Optional: for image model
try:
    import tensorflow as tf
    from PIL import Image
except Exception:
    tf = None

# ---------- Config ----------
PORT = int(os.environ.get("PORT", 7860))
HOST = os.environ.get("HOST", "0.0.0.0")
URL_MODEL_PATH = os.environ.get("URL_MODEL_PATH", "model_compressed.joblib")
IMAGE_MODEL_PATH = os.environ.get("IMAGE_MODEL_PATH", "image_model_c_int8.tflite")

PHISH_HIGH = float(os.environ.get("PHISH_HIGH", 0.7))
PHISH_LOW = float(os.environ.get("PHISH_LOW", 0.3))

# ---------- App setup ----------
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("phish-backend")
logger.info("πŸš€ Starting Phish Detection Backend...")

# ---------- Load Models ----------
url_model = None
image_interpreter = None
input_details = output_details = None

try:
    if os.path.exists(URL_MODEL_PATH):
        logger.info(f"Loading URL model from {URL_MODEL_PATH}")
        url_model = joblib.load(URL_MODEL_PATH)
        logger.info("βœ… URL model loaded successfully")
    else:
        logger.warning(f"⚠️ URL model not found at {URL_MODEL_PATH}")
except Exception as e:
    logger.exception("❌ Failed to load URL model: %s", e)
    url_model = None

if tf is not None:
    try:
        if os.path.exists(IMAGE_MODEL_PATH):
            logger.info(f"Loading image model from {IMAGE_MODEL_PATH}")
            image_interpreter = tf.lite.Interpreter(model_path=IMAGE_MODEL_PATH)
            image_interpreter.allocate_tensors()
            input_details = image_interpreter.get_input_details()
            output_details = image_interpreter.get_output_details()
            logger.info("βœ… Image model loaded successfully")
        else:
            logger.warning(f"⚠️ Image model not found at {IMAGE_MODEL_PATH}")
    except Exception as e:
        logger.exception("❌ Failed to load image model: %s", e)
        image_interpreter = None
else:
    logger.warning("⚠️ TensorFlow not available; image model disabled")

# ---------- Helpers ----------
def score_to_category(score: float):
    """Convert probability to phishing category."""
    try:
        s = float(score)
    except Exception:
        s = 0.5
    if s >= PHISH_HIGH:
        return "phish", "red", "🚨 This link/image is likely PHISH (high risk)"
    if s < PHISH_LOW:
        return "not_phish", "green", "βœ… This appears safe (low risk)"
    return "uncertain", "yellow", "⚠️ Uncertain β€” needs manual review"

def preprocess_url_for_model(url: str, max_len: int = 200):
    url = (url or "").lower()
    x = [ord(c) for c in url[:max_len]]
    if len(x) < max_len:
        x += [0] * (max_len - len(x))
    return np.array([x])

def get_url_score_from_model(model, url: str):
    if model is None:
        raise RuntimeError("URL model not loaded")
    x = preprocess_url_for_model(url)
    try:
        if hasattr(model, "predict_proba"):
            proba = model.predict_proba(x)
            return float(proba[0][1])
    except Exception:
        pass
    pred = model.predict(x)
    return float(pred[0]) if pred[0] <= 1 else 1.0

def get_image_score_from_tflite(interpreter, file_storage):
    if interpreter is None:
        raise RuntimeError("Image interpreter not loaded")
    img = Image.open(file_storage).convert("RGB").resize((224, 224))
    arr = np.array(img, dtype=np.float32) / 255.0
    arr = np.expand_dims(arr, axis=0)
    interpreter.set_tensor(input_details[0]["index"], arr)
    interpreter.invoke()
    out = interpreter.get_tensor(output_details[0]["index"]).squeeze()
    if out.ndim == 0 or out.size == 1:
        score = float(out)
    else:
        score = float(out[1]) if len(out) > 1 else float(np.max(out))
    return max(0.0, min(1.0, score))

# ---------- Routes ----------
@app.route("/", methods=["GET"])
def health():
    return jsonify({
        "status": "ok",
        "message": "βœ… Backend running properly!",
        "endpoints": [
            "/scan/url",
            "/scan/image",
            "/update/feedback",
            "/run/predict"
        ]
    }), 200

@app.route("/scan/url", methods=["POST"])
def scan_url():
    data = request.get_json(silent=True, force=True)
    if not data or "url" not in data:
        return jsonify({"error": "Missing 'url'"}), 400

    url = data["url"]
    logger.info(f"Scanning URL: {url}")
    try:
        score = get_url_score_from_model(url_model, url) if url_model else 0.5
    except Exception as e:
        logger.exception("URL scan failed: %s", e)
        score = 0.5

    category, color, human_msg = score_to_category(score)
    return jsonify({
        "endpoint": "/scan/url",
        "url": url,
        "score": score,
        "category": category,
        "color": color,
        "human_message": human_msg,
        "message": "βœ… URL Scan Backend Working Perfectly!"
    }), 200

@app.route("/scan/image", methods=["POST"])
def scan_image():
    if "file" not in request.files:
        return jsonify({"error": "Missing 'file'"}), 400

    file = request.files["file"]
    logger.info(f"Scanning image: {file.filename}")
    try:
        score = get_image_score_from_tflite(image_interpreter, file) if image_interpreter else 0.5
    except Exception as e:
        logger.exception("Image scan failed: %s", e)
        score = 0.5

    category, color, human_msg = score_to_category(score)
    return jsonify({
        "endpoint": "/scan/image",
        "filename": file.filename,
        "score": score,
        "category": category,
        "color": color,
        "human_message": human_msg,
        "message": "βœ… Image Scan Backend Working Perfectly!"
    }), 200

@app.route("/update/feedback", methods=["POST"])
def update_feedback():
    data = request.get_json(silent=True, force=True)
    if not data:
        return jsonify({"error": "Missing JSON body"}), 400
    logger.info(f"Feedback received: {data}")
    try:
        with open("feedback.log", "a", encoding="utf-8") as f:
            f.write(str(data) + "\n")
    except Exception as e:
        logger.warning("Could not save feedback: %s", e)
    return jsonify({
        "status": "success",
        "message": "βœ… Feedback received successfully!",
        "stored": True,
        "data": data
    }), 200

@app.route("/run/predict", methods=["POST"])
def run_predict():
    data = request.get_json(silent=True, force=True)
    if not data or "data" not in data:
        return jsonify({"error": "Missing 'data'"}), 400
    text = data["data"][0]
    logger.info(f"Predict endpoint: {text}")
    try:
        score = get_url_score_from_model(url_model, text) if url_model else 0.5
    except Exception as e:
        logger.exception("Prediction failed: %s", e)
        score = 0.5
    category, color, human_msg = score_to_category(score)
    return jsonify({
        "endpoint": "/run/predict",
        "input": text,
        "score": score,
        "category": category,
        "color": color,
        "human_message": human_msg,
        "message": "βœ… Prediction Endpoint Working Perfectly!"
    }), 200

# ---------- Run ----------
if __name__ == "__main__":
    logger.info(f"βœ… Server starting on {HOST}:{PORT}")
    app.run(host=HOST, port=PORT)