Spaces:
Sleeping
Sleeping
Create app
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117from flask import Flask, request, jsonifyfrom flask_cors import CORSimport numpy as npimport joblibimport osimport tensorflow as tffrom tensorflow.keras.preprocessing import imagefrom huggingface_hub import hf_hub_download
app = Flask(__name__)CORS(app, resources={r"/*": {"origins": "https://webrakshak.vercel.app"}})
@app.after_requestdef add_cors_headers(response): response.headers.add('Access-Control-Allow-Origin', 'https://webrakshak.vercel.app') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,POST,OPTIONS') return response
# === Hugging Face model repo ===HF_REPO_ID = "https://huggingface.co/spaces/OnArchit/phish_detection_model/new/main" URL_MODEL_FILE = "url_model.joblib"IMAGE_MODEL_FILE = "image_model.tflite"
MODEL_DIR = "models"os.makedirs(MODEL_DIR, exist_ok=True)
# === Download models from Hugging Face ===def get_model_from_hf(repo_id, filename): print(f"⬇️ Fetching {filename} from Hugging Face Hub...") local_path = hf_hub_download(repo_id=repo_id, filename=filename, local_dir=MODEL_DIR) print(f"✅ Loaded from {local_path}") return local_path
try: url_model_path = get_model_from_hf(HF_REPO_ID, URL_MODEL_FILE) url_model = joblib.load(url_model_path) print("✅ URL model loaded")except Exception as e: print("⚠️ URL model load failed:", e) url_model = None
try: image_model_path = get_model_from_hf(HF_REPO_ID, IMAGE_MODEL_FILE) interpreter = tf.lite.Interpreter(model_path=image_model_path) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() print("✅ Image model loaded")except Exception as e: print("⚠️ Image model load failed:", e) interpreter = None input_details = output_details = None
# === URL Scan ===def preprocess_url(url): url = url.lower() max_len = 200 x = [ord(c) for c in url[:max_len]] if len(x) < max_len: x += [0] * (max_len - len(x)) return np.array([x])
@app.route("/scan/url", methods=["POST"])def scan_url(): data = request.get_json() url = data.get("url") if not url: return jsonify({"error": "Missing URL"}), 400 if url_model is None: return jsonify({"error": "URL model not loaded"}), 500
try: x = preprocess_url(url) score = float(url_model.predict_proba(x)[0][1]) except Exception: score = 0.5 phishing = score > 0.5 return jsonify({"score": score, "phishing": phishing})
# === Image Scan ===@app.route("/scan/image", methods=["POST"])def scan_image(): if "image" not in request.files: return jsonify({"error": "No image uploaded"}), 400 if interpreter is None: return jsonify({"error": "Image model not loaded"}), 500
img_file = request.files["image"] img = image.load_img(img_file, target_size=(224, 224)) x = image.img_to_array(img) / 255.0 x = np.expand_dims(x, axis=0).astype(np.float32)
try: interpreter.set_tensor(input_details[0]['index'], x) interpreter.invoke() score = float(interpreter.get_tensor(output_details[0]['index'])[0][0]) except Exception: score = 0.5 phishing = score > 0.5 return jsonify({"score": score, "phishing": phishing})
# === Health check ===@app.route("/")def home(): return jsonify({"status": "running", "message": "Backend connected to Hugging Face models"})
if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host="0.0.0.0", port=port)appAdded+117