# 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)