handex commited on
Commit
3bad285
Β·
verified Β·
1 Parent(s): 3ef13e1

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +75 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,77 @@
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
+ # --- Configuration ---
6
+ MODEL_PATH = 'src/customer_model.joblib'
7
+ SCALER_PATH = 'src/scaler.joblib'
8
+
9
+ FEATURES = ['Income', 'Seniority', 'Spending']
10
+
11
+ @st.cache_resource
12
+ def load_assets():
13
+ try:
14
+ model = joblib.load(MODEL_PATH)
15
+ scaler = joblib.load(SCALER_PATH)
16
+ return model, scaler
17
+ except FileNotFoundError:
18
+ st.error(f"Error: Model or Scaler file not found. Ensure both '{MODEL_PATH}' and '{SCALER_PATH}' are uploaded to the Space.")
19
+ return None, None
20
+ except Exception as e:
21
+ st.error(f"Error loading assets: {e}")
22
+ return None, None
23
+
24
+ def predict_cluster(model, scaler, input_data):
25
+ input_df = pd.DataFrame([input_data])
26
+
27
+ scaled_data = scaler.transform(input_df[FEATURES])
28
+
29
+ prediction = model.predict(scaled_data)
30
+
31
+ return prediction[0]
32
+
33
+ # --- Streamlit Interface ---
34
+ st.set_page_config(page_title="Customer Clustering App", layout="wide")
35
+ st.title("πŸ₯‡ Customer Personality Cluster Prediction")
36
+ st.markdown("Use the sidebar to input customer features and predict their cluster.")
37
+
38
+ model, scaler = load_assets()
39
+
40
+ if model is not None and scaler is not None:
41
+ st.sidebar.header("Input Customer Features")
42
+
43
+ income = st.sidebar.slider("Income ($):", min_value=1000, max_value=200000, value=50000)
44
+ seniority = st.sidebar.slider("Seniority (Years as customer):", min_value=0, max_value=50, value=10)
45
+ spending = st.sidebar.slider("Total Spending ($):", min_value=0, max_value=3000, value=500)
46
+
47
+ input_data = {
48
+ 'Income': income,
49
+ 'Seniority': seniority,
50
+ 'Spending': spending
51
+ }
52
+
53
+ st.subheader("Current Input Data:")
54
+ st.write(pd.DataFrame([input_data]))
55
+
56
+ if st.button("Predict Cluster"):
57
+ with st.spinner('Predicting...'):
58
+ cluster_id = predict_cluster(model, scaler, input_data)
59
+
60
+ cluster_descriptions = {
61
+ 0: "πŸ‘‘ **Cluster 0: High Potential**",
62
+ 1: "🚨 **Cluster 1: Need Attention**",
63
+ 2: "⏳ **Cluster 2: Leaky Bucket**",
64
+ 3: "⭐ **Cluster 3: Stars**",
65
+ # Add more cluster IDs and descriptions here if needed
66
+ }
67
+
68
+ description = cluster_descriptions.get(cluster_id, f"πŸ” Cluster ID **{cluster_id}** (Undefined)")
69
+
70
+ st.success(f"Prediction Complete! The customer belongs to:")
71
+ st.markdown(f"## {description}")
72
+
73
 
74
+ 0: '',
75
+ 1: '',
76
+ 2: '',
77
+ 3: ''})