EnYa32 commited on
Commit
46c5a60
·
verified ·
1 Parent(s): 00965f5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +71 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,73 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import joblib
4
+
5
+ st.set_page_config(page_title="Payment Fraud Detection", page_icon="💳", layout="centered")
6
+
7
+ @st.cache_resource
8
+ def load_artifacts():
9
+ model = joblib.load("src/randomforest_model.pkl")
10
+ try:
11
+ features = joblib.load("model_features.pkl")
12
+ except Exception:
13
+ features = None
14
+ return model, features
15
+
16
+ model, model_features = load_artifacts()
17
+
18
+ st.title("💳 Payment Fraud Detection")
19
+ st.write("Enter transaction details and get a fraud prediction (0 = Not Fraud, 1 = Fraud).")
20
+
21
+ with st.sidebar:
22
+ st.header("ℹ️ Info")
23
+ st.write("**Model:** Random Forest")
24
+ if model_features is None:
25
+ st.warning("`model_features.pkl` not found. App will try to predict without reindexing columns.")
26
+ else:
27
+ st.caption(f"Loaded {len(model_features)} feature columns.")
28
+
29
+ st.subheader("Transaction Input")
30
+
31
+ col1, col2 = st.columns(2)
32
+ with col1:
33
+ accountAgeDays = st.number_input("accountAgeDays", min_value=0, value=30, step=1)
34
+ numItems = st.number_input("numItems", min_value=1, value=1, step=1)
35
+ with col2:
36
+ localTime = st.number_input("localTime (e.g., 0–24)", min_value=0.0, value=12.0, step=0.5)
37
+ paymentMethodAgeDays = st.number_input("paymentMethodAgeDays", min_value=0, value=10, step=1)
38
+
39
+ paymentMethod = st.selectbox("paymentMethod", ["paypal", "creditcard", "storecredit"])
40
+
41
+ if st.button("Predict", type="primary"):
42
+ # Build one-row dataframe exactly like training input BEFORE get_dummies
43
+ input_df = pd.DataFrame([{
44
+ "accountAgeDays": accountAgeDays,
45
+ "numItems": numItems,
46
+ "localTime": localTime,
47
+ "paymentMethodAgeDays": paymentMethodAgeDays,
48
+ "paymentMethod": paymentMethod
49
+ }])
50
+
51
+ # One-hot encode like training
52
+ X = pd.get_dummies(input_df, drop_first=True)
53
+
54
+ # Align columns to training columns (important!)
55
+ if model_features is not None:
56
+ X = X.reindex(columns=model_features, fill_value=0)
57
+
58
+ # Predict
59
+ pred = model.predict(X)[0]
60
+ proba = None
61
+ if hasattr(model, "predict_proba"):
62
+ proba = model.predict_proba(X)[0][1]
63
+
64
+ st.divider()
65
+ if pred == 1:
66
+ st.error("🚨 Prediction: FRAUD (1)")
67
+ else:
68
+ st.success("✅ Prediction: NOT FRAUD (0)")
69
+
70
+ if proba is not None:
71
+ st.metric("Fraud Probability", f"{proba:.2%}")
72
 
73
+ st.caption("Tip: If you get column mismatch issues, create `model_features.pkl` (see README).")