Spaces:
Sleeping
Sleeping
Update app.py
Browse files12123545678101112131415161718192021229101112131415161718192021221 unmodified line2425263031323334353637383940414243444546474849505152535455565758596061626327282930313233343536373839404142434445464748495051525354555657585960616263646566672 unmodified lines707172727374757677787980737475767778827980818287888384909192939495968598868788899091925 unmodified lines9899100110111112113114115116117118119120121122123124125126127128129101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134from flask import Flask, request, jsonifyfrom flask_cors import CORSimport streamlit as stimport numpy as npimport joblibimport osimport tensorflow as tffrom tensorflow.keras.preprocessing import imagefrom huggingface_hub import hf_hub_downloadimport os
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 = "OnArchit/phish_detection_model" # β
Correct repo ID# ---------------------------# π― 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)
# === 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 = None input_details = output_details = None
# === URL Scan ===def preprocess_url(url):@st.cache_resourcedef load_models(): """Download and load both URL and Image models from Hugging Face Hub""" try: # URL model st.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 = None
try: # Image model st.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 = None input_details = output_details = None
return url_model, interpreter, input_details, output_details
url_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 = 200 x = [ord(c) for c in url[:max_len]]2 unmodified lines 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
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: 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})
return score, "π₯ Phishing" if phishing else "π© Safe"
# === 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"]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.0 x = np.expand_dims(x, axis=0).astype(np.float32)5 unmodified lines 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", "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)
return 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