import streamlit as st import pandas as pd import joblib st.set_page_config(page_title="Payment Fraud Detection", page_icon="đŸ’ŗ", layout="centered") @st.cache_resource def load_artifacts(): model = joblib.load("src/randomforest_model.pkl") try: features = joblib.load("src/model_features.pkl") except Exception: features = None return model, features model, model_features = load_artifacts() st.title("đŸ’ŗ Payment Fraud Detection") st.write("Enter transaction details and get a fraud prediction (0 = Not Fraud, 1 = Fraud).") with st.sidebar: st.header("â„šī¸ Info") st.write("**Model:** Random Forest") if model_features is None: st.warning("`model_features.pkl` not found. App will try to predict without reindexing columns.") else: st.caption(f"Loaded {len(model_features)} feature columns.") st.subheader("Transaction Input") col1, col2 = st.columns(2) with col1: accountAgeDays = st.number_input("accountAgeDays", min_value=0, value=30, step=1) numItems = st.number_input("numItems", min_value=1, value=1, step=1) with col2: localTime = st.number_input("localTime (e.g., 0–24)", min_value=0.0, value=12.0, step=0.5) paymentMethodAgeDays = st.number_input("paymentMethodAgeDays", min_value=0, value=10, step=1) paymentMethod = st.selectbox("paymentMethod", ["paypal", "creditcard", "storecredit"]) if st.button("Predict", type="primary"): # Build one-row dataframe exactly like training input BEFORE get_dummies input_df = pd.DataFrame([{ "accountAgeDays": accountAgeDays, "numItems": numItems, "localTime": localTime, "paymentMethodAgeDays": paymentMethodAgeDays, "paymentMethod": paymentMethod }]) # One-hot encode like training X = pd.get_dummies(input_df, drop_first=True) # Align columns to training columns (important!) if model_features is not None: X = X.reindex(columns=model_features, fill_value=0) # Predict pred = model.predict(X)[0] proba = None if hasattr(model, "predict_proba"): proba = model.predict_proba(X)[0][1] st.divider() if pred == 1: st.error("🚨 Prediction: FRAUD (1)") else: st.success("✅ Prediction: NOT FRAUD (0)") if proba is not None: st.metric("Fraud Probability", f"{proba:.2%}") st.caption("Tip: If you get column mismatch issues, create `model_features.pkl` (see README).")