Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768696 unmodified linesimport osimport tflite_runtime.interpreter as tflite# --- Hugging Face Repo Details ---HF_REPO_ID = "OnArchit/phish_detection_model"URL_MODEL_FILE = "model_compressed.joblib"IMAGE_MODEL_FILE = "image_model_c_int8.tflite"# --- Download models if not already ---MODEL_DIR = "models"os.makedirs(MODEL_DIR, exist_ok=True)@st.cache_resourcedef load_models():st.write("π₯ Downloading models from Hugging Face...")url_model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=URL_MODEL_FILE, local_dir=MODEL_DIR)image_model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=IMAGE_MODEL_FILE, local_dir=MODEL_DIR)url_model = joblib.load(url_model_path)interpreter = tflite.Interpreter(model_path=image_model_path)interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()return url_model, interpreter, input_details, output_detailsurl_model, interpreter, input_details, output_details = load_models()# --- Streamlit UI ---st.title("π‘οΈ Phish Detection System")st.write("Detect phishing URLs and images with lightweight AI models hosted on Hugging Face π")tab1, tab2 = st.tabs(["π URL Scanner", "πΌοΈ Image Scanner"])# --- URL Scanner ---with tab1:url_input = st.text_input("Enter URL:")if st.button("Scan URL"):if url_input:x = [ord(c) for c in url_input.lower()[:200]]if len(x) < 200:x += [0] * (200 - len(x))x = np.array([x])score = float(url_model.predict_proba(x)[0][1])st.metric("Phishing Probability", f"{score*100:.2f}%")st.success("β Safe URL") if score < 0.5 else st.error("β οΈ Phishing Detected!")else:st.warning("Please enter a URL.")# --- Image Scanner ---with tab2:uploaded_file = st.file_uploader("Upload a website screenshot:", type=["jpg", "png", "jpeg"])if uploaded_file:img = Image.open(uploaded_file).convert("RGB").resize((224, 224))st.image(img, caption="Uploaded Image", use_container_width=True)img_array = np.expand_dims(np.array(img) / 255.0, axis=0).astype(np.float32)interpreter.set_tensor(input_details[0]['index'], img_array)interpreter.invoke()score = float(interpreter.get_tensor(output_details[0]['index'])[0][0])st.metric("Phishing Probability", f"{score*100:.2f}%")st.success("β Safe Image") if score < 0.5 else st.error("β οΈ Phishing Detected!")6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141156 unmodified linesimport osimport tflite_runtime.interpreter as tflite# --- Page setup ---st.set_page_config(page_title="π‘οΈ Phish Detector", page_icon="π§ ", layout="centered")st.title("π‘οΈ Phish Detection Model")st.markdown("Check URLs and website screenshots for phishing risk π")# --- Hugging Face repo and model names ---HF_REPO_ID = "OnArchit/phish_detection_model"URL_MODEL_FILE = "model_compressed.joblib"IMAGE_MODEL_FILE = "image_model_c_int8.tflite"MODEL_DIR = "models"os.makedirs(MODEL_DIR, exist_ok=True)# --- Model loading with spinner ---@st.cache_resource(show_spinner=False)def load_models():with st.spinner("β³ Downloading and initializing models..."):try:url_model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=URL_MODEL_FILE, local_dir=MODEL_DIR)url_model = joblib.load(url_model_path)image_model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=IMAGE_MODEL_FILE, local_dir=MODEL_DIR)interpreter = tflite.Interpreter(model_path=image_model_path)interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()st.success("β Models loaded successfully!")return url_model, interpreter, input_details, output_detailsexcept Exception as e:st.error(f"β οΈ Model loading failed: {e}")return None, None, None, Noneurl_model, interpreter, input_details, output_details = load_models()# --- URL Preprocessing ---def preprocess_url(url):url = url.lower()max_len = 200x = [ord(c) for c in url[:max_len]]if len(x) < max_len:x += [0] * (max_len - len(x))return np.array([x])# --- Image Preprocessing ---def preprocess_image(img):img = img.resize((224, 224))img_array = np.array(img) / 255.0img_array = np.expand_dims(img_array, axis=0).astype(np.float32)return img_array# --- Tabs for URL and Image Detection ---tab1, tab2 = st.tabs(["π URL Detection", "πΌοΈ Image Detection"])# --- URL Detection ---with tab1:st.subheader("π Check URL for Phishing")url_input = st.text_input("Enter website URL:")if st.button("Scan URL"):if not url_input.strip():st.warning("β οΈ Please enter a valid URL.")elif url_model is None:st.error("β URL model not loaded.")else:with st.spinner("π Scanning URL..."):x = preprocess_url(url_input)try:score = float(url_model.predict_proba(x)[0][1])except Exception:score = 0.5phishing = score > 0.5if phishing:st.error(f"π¨ Phishing Detected! (Score: {score:.2f})")else:st.success(f"β Safe URL (Score: {score:.2f})")# --- Image Detection ---with tab2:st.subheader("πΌοΈ Check Website Screenshot")uploaded_file = st.file_uploader("Upload website screenshot", type=["jpg", "jpeg", "png"])if uploaded_file:image = Image.open(uploaded_file).convert("RGB")img_array = preprocess_image(image)if interpreter is None:st.error("β Image model not loaded.")else:with st.spinner("π§ Analyzing image..."):interpreter.set_tensor(input_details[0]['index'], img_array)interpreter.invoke()score = float(interpreter.get_tensor(output_details[0]['index'])[0][0])phishing = score > 0.5st.image(image, caption="Uploaded Screenshot", use_container_width=True)if phishing:st.error(f"π¨ Phishing Website Detected! (Score: {score:.2f})")else:st.success(f"β Safe Website (Score: {score:.2f})")st.markdown("---")st.caption("Developed by Archit Kumar | Powered by Hugging Face π€")
app.py+83-37