Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324251 unmodified line272829303132333435363738394041424344454647484950515253545556575859606162636465662 unmodified lines697071727374757677787980818283848586878889909192939495969798991001015 unmodified lines107108109110111112113114115116117118119120121122123124125126127128129from 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_downloadapp = 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 = "OnArchit/phish_detection_model" # β Correct repo IDURL_MODEL_FILE = "model_compressed.joblib"IMAGE_MODEL_FILE = "image_model_c_int8.tflite"1 unmodified lineos.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# === Load URL model ===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# === Load image model ===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 = Noneinput_details = output_details = None# === URL Scan ===def preprocess_url(url):url = url.lower()max_len = 200x = [ord(c) for c in url[:max_len]]2 unmodified linesreturn 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"}), 400if url_model is None:return jsonify({"error": "URL model not loaded"}), 500try:x = preprocess_url(url)score = float(url_model.predict_proba(x)[0][1])except Exception:score = 0.5phishing = score > 0.5return 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"}), 400if interpreter is None:return jsonify({"error": "Image model not loaded"}), 500img_file = request.files["image"]img = image.load_img(img_file, target_size=(224, 224))x = image.img_to_array(img) / 255.0x = np.expand_dims(x, axis=0).astype(np.float32)5 unmodified linesexcept Exception:score = 0.5phishing = score > 0.5return jsonify({"score": score, "phishing": phishing})# === Health check ===@app.route("/")def home():return jsonify({"status": "running","message": "Backend connected to Hugging Face models","models": {"url_model": "β " if url_model else "β","image_model": "β " if interpreter else "β"}})if __name__ == "__main__":port = int(os.environ.get("PORT", 5000))app.run(host="0.0.0.0", port=port)123456789101112131415161718192021221 unmodified line24252627282930313233343536373839404142434445464748495051525354555657585960616263646566672 unmodified lines70717273747576777879808182838485868788899091925 unmodified lines9899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import streamlit as stimport numpy as npimport joblibimport tensorflow as tffrom tensorflow.keras.preprocessing import imagefrom huggingface_hub import hf_hub_downloadimport os# ---------------------------# π― App Configuration# ---------------------------st.set_page_config(page_title="Phish Detection Model", page_icon="π", layout="centered")st.title("π Phish Detection Model")st.markdown("### π§ Safe Click Environment β Detect phishing URLs and fake website screenshots")# ---------------------------# π¦ Model Download Section# ---------------------------REPO_ID = "OnArchit/phish_detection_model" # Change to your repo if differentURL_MODEL_FILE = "model_compressed.joblib"IMAGE_MODEL_FILE = "image_model_c_int8.tflite"1 unmodified lineos.makedirs(MODEL_DIR, exist_ok=True)@st.cache_resourcedef load_models():"""Download and load both URL and Image models from Hugging Face Hub"""try:# URL modelst.info("π₯ Downloading URL model from Hugging Face...")url_model_path = hf_hub_download(repo_id=REPO_ID, filename=URL_MODEL_FILE, local_dir=MODEL_DIR)url_model = joblib.load(url_model_path)st.success("β URL Model Loaded Successfully")except Exception as e:st.error(f"β οΈ Failed to load URL model: {e}")url_model = Nonetry:# Image modelst.info("π₯ Downloading Image model from Hugging Face...")image_model_path = hf_hub_download(repo_id=REPO_ID, filename=IMAGE_MODEL_FILE, local_dir=MODEL_DIR)interpreter = tf.lite.Interpreter(model_path=image_model_path)interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()st.success("β Image Model Loaded Successfully")except Exception as e:st.error(f"β οΈ Failed to load Image model: {e}")interpreter = Noneinput_details = output_details = Nonereturn url_model, interpreter, input_details, output_detailsurl_model, interpreter, input_details, output_details = load_models()# ---------------------------# π§© Utility Functions# ---------------------------def preprocess_url(url: str):"""Convert URL string into numeric sequence for model input"""url = url.lower()max_len = 200x = [ord(c) for c in url[:max_len]]2 unmodified linesreturn np.array([x])def predict_url(url: str):"""Predict phishing probability for URL"""if not url_model:return 0.5, "Model not loaded"x = preprocess_url(url)try:score = float(url_model.predict_proba(x)[0][1])except Exception:score = 0.5phishing = score > 0.5return score, "π₯ Phishing" if phishing else "π© Safe"def predict_image(img_file):"""Predict phishing probability for website image"""if not interpreter:return 0.5, "Model not loaded"img = image.load_img(img_file, target_size=(224, 224))x = image.img_to_array(img) / 255.0x = np.expand_dims(x, axis=0).astype(np.float32)5 unmodified linesexcept Exception:score = 0.5phishing = score > 0.5return score, "π₯ Phishing" if phishing else "π© Safe"# ---------------------------# π§ Streamlit UI# ---------------------------st.sidebar.header("Choose Scan Type π")scan_type = st.sidebar.radio("Select Input Type:", ["URL Scanner", "Image Scanner"])if scan_type == "URL Scanner":st.subheader("π Check Website URL")url_input = st.text_input("Enter the website URL here:")if st.button("Scan URL"):if url_input.strip():with st.spinner("Analyzing URL..."):score, result = predict_url(url_input)st.metric(label="Detection Result", value=result, delta=f"{score*100:.2f}% confidence")else:st.warning("β οΈ Please enter a URL.")elif scan_type == "Image Scanner":st.subheader("πΌοΈ Upload Screenshot of Website")img_file = st.file_uploader("Upload an image (JPG/PNG)", type=["jpg", "jpeg", "png"])if img_file:st.image(img_file, caption="Uploaded Website Screenshot", use_column_width=True)if st.button("Scan Image"):with st.spinner("Analyzing Image..."):score, result = predict_image(img_file)st.metric(label="Detection Result", value=result, delta=f"{score*100:.2f}% confidence")# ---------------------------# β Footer# ---------------------------st.markdown("---")st.caption("Β© 2025 OnArchit | Built with β€οΈ using Streamlit + Hugging Face Hub")
app.py+95-90