EnYa32 commited on
Commit
f93716d
·
verified ·
1 Parent(s): c279be8

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +140 -36
src/streamlit_app.py CHANGED
@@ -1,40 +1,144 @@
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 os
2
+ import random
3
+ import joblib
4
  import numpy as np
5
  import pandas as pd
6
  import streamlit as st
7
+ from sklearn.metrics.pairwise import cosine_similarity
8
 
9
+
10
+ st.set_page_config(page_title="Amazon Electronics Recommender", page_icon="🛒", layout="wide")
11
+
12
+ st.title("🛒 Amazon Electronics Product Recommender")
13
+ st.caption("Item-based Collaborative Filtering (Sparse User–Item Matrix + Cosine Similarity)")
14
+
15
+ ARTIFACT_R = "src/R_sparse.pkl"
16
+ ARTIFACT_PRODUCTS = "src/product_ids.pkl"
17
+ ARTIFACT_MAP = "src/prod_to_idx.pkl"
18
+
19
+
20
+ @st.cache_resource
21
+ def load_artifacts():
22
+ # Helpful debugging info (especially on HuggingFace)
23
+ files_here = os.listdir(".")
24
+ required = [ARTIFACT_R, ARTIFACT_PRODUCTS, ARTIFACT_MAP]
25
+ missing = [f for f in required if f not in files_here]
26
+
27
+ if missing:
28
+ raise FileNotFoundError(
29
+ f"Missing files: {missing}\n\n"
30
+ f"Current folder files: {files_here}\n\n"
31
+ f"Please upload the .pkl artifacts to the repo root (same folder as app.py)."
32
+ )
33
+
34
+ R = joblib.load(ARTIFACT_R) # scipy.sparse csr_matrix
35
+ product_ids = joblib.load(ARTIFACT_PRODUCTS) # pandas Index / array-like
36
+ prod_to_idx = joblib.load(ARTIFACT_MAP) # dict: product_id -> index
37
+
38
+ # Ensure product_ids is a numpy array for indexing
39
+ product_ids = np.array(list(product_ids))
40
+
41
+ return R, product_ids, prod_to_idx
42
+
43
+
44
+ def recommend_sparse(R, product_ids, prod_to_idx, product_id: str, top_n: int = 10, min_sim: float = 0.01):
45
+ if product_id not in prod_to_idx:
46
+ return pd.DataFrame({"message": ["Product not found. Please try another product_id."]})
47
+
48
+ j = prod_to_idx[product_id]
49
+
50
+ # 1 x users (sparse row vector)
51
+ item_vec = R[:, j].T
52
+
53
+ # similarity against all items (1 x items)
54
+ sims = cosine_similarity(item_vec, R.T).ravel()
55
+
56
+ # remove itself
57
+ sims[j] = -1.0
58
+
59
+ # keep only sims >= threshold
60
+ valid = np.where(sims >= float(min_sim))[0]
61
+ if valid.size == 0:
62
+ return pd.DataFrame({"message": [f"No recommendations found with min_sim >= {min_sim}. Try lowering the threshold."]})
63
+
64
+ # take top_n among valid
65
+ top_idx = valid[np.argsort(sims[valid])[::-1][:top_n]]
66
+
67
+ out = pd.DataFrame({
68
+ "recommended_product_id": product_ids[top_idx],
69
+ "similarity": sims[top_idx].astype(float)
70
+ })
71
+
72
+ return out
73
+
74
+
75
+ # Sidebar
76
+ st.sidebar.header("⚙️ Settings")
77
+
78
+ try:
79
+ R, product_ids, prod_to_idx = load_artifacts()
80
+ st.sidebar.success("Artifacts loaded successfully.")
81
+ except Exception as e:
82
+ st.sidebar.error("Artifacts could not be loaded.")
83
+ st.error(str(e))
84
+ st.stop()
85
+
86
+ st.sidebar.write("**Dataset scope (your reduced subset):**")
87
+ st.sidebar.write(f"- Users: **{R.shape[0]:,}**")
88
+ st.sidebar.write(f"- Products: **{R.shape[1]:,}**")
89
+ st.sidebar.write(f"- Interactions (non-zeros): **{R.nnz:,}**")
90
+
91
+ top_n = st.sidebar.slider("Top-N recommendations", min_value=3, max_value=30, value=10, step=1)
92
+ min_sim = st.sidebar.slider("Minimum similarity threshold", min_value=0.0, max_value=0.20, value=0.01, step=0.01)
93
+
94
+ st.divider()
95
+
96
+ # Main UI
97
+ col1, col2 = st.columns([2, 1], gap="large")
98
+
99
+ with col1:
100
+ st.subheader("🔎 Find similar products")
101
+ product_id = st.text_input("Enter a product_id (ASIN)", value="")
102
+
103
+ run = st.button("Recommend", type="primary", use_container_width=True)
104
+
105
+ if run:
106
+ product_id = product_id.strip()
107
+ if not product_id:
108
+ st.warning("Please enter a product_id.")
109
+ else:
110
+ with st.spinner("Computing recommendations..."):
111
+ recs = recommend_sparse(R, product_ids, prod_to_idx, product_id, top_n=top_n, min_sim=min_sim)
112
+
113
+ if "message" in recs.columns:
114
+ st.info(recs["message"].iloc[0])
115
+ else:
116
+ st.success(f"Recommendations for: **{product_id}**")
117
+ st.dataframe(recs, use_container_width=True)
118
+
119
+ with col2:
120
+ st.subheader("🧪 Quick test")
121
+ st.write("Try a random product_id from the available set:")
122
+
123
+ if st.button("Pick random product_id", use_container_width=True):
124
+ pid = random.choice(product_ids.tolist())
125
+ st.session_state["random_pid"] = pid
126
+
127
+ if "random_pid" in st.session_state:
128
+ st.code(st.session_state["random_pid"])
129
+ if st.button("Recommend for random product_id", use_container_width=True):
130
+ pid = st.session_state["random_pid"]
131
+ with st.spinner("Computing recommendations..."):
132
+ recs = recommend_sparse(R, product_ids, prod_to_idx, pid, top_n=top_n, min_sim=min_sim)
133
+
134
+ if "message" in recs.columns:
135
+ st.info(recs["message"].iloc[0])
136
+ else:
137
+ st.success(f"Recommendations for: **{pid}**")
138
+ st.dataframe(recs, use_container_width=True)
139
+
140
+ st.divider()
141
+ st.caption(
142
+ "Note: This demo uses a reduced subset of the original dataset "
143
+ "(top products + most active users) and computes cosine similarity on-the-fly."
144
+ )