File size: 5,756 Bytes
f93716d
 
 
7b33aeb
 
 
f93716d
7b33aeb
4d2e2f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e368430
 
4d2e2f1
 
 
 
e368430
4d2e2f1
 
 
f93716d
 
 
4d2e2f1
f93716d
 
 
 
4d2e2f1
 
f93716d
 
4d2e2f1
 
 
f93716d
 
 
 
4d2e2f1
 
 
 
 
 
 
 
 
 
 
f93716d
4d2e2f1
 
 
f93716d
 
 
4d2e2f1
f93716d
 
4d2e2f1
f93716d
 
4d2e2f1
f93716d
 
 
 
4d2e2f1
 
 
f93716d
 
 
4d2e2f1
f93716d
 
 
 
4d2e2f1
f93716d
4d2e2f1
f93716d
 
 
 
 
 
 
 
 
 
4d2e2f1
f93716d
 
4d2e2f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f93716d
 
 
4d2e2f1
f93716d
4d2e2f1
f93716d
 
 
 
4d2e2f1
 
 
 
f93716d
4d2e2f1
f93716d
 
 
 
 
4d2e2f1
 
 
 
f93716d
 
 
 
4d2e2f1
f93716d
 
 
 
4d2e2f1
f93716d
 
4d2e2f1
f93716d
 
 
 
 
 
4d2e2f1
 
 
 
f93716d
 
 
 
4d2e2f1
f93716d
 
 
 
 
4d2e2f1
 
f93716d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import os
import random
import joblib
import numpy as np
import pandas as pd
import streamlit as st
from sklearn.metrics.pairwise import cosine_similarity

# --------------------------------------------------
# Paths (HuggingFace-safe)
# --------------------------------------------------
REPO_ROOT = os.getcwd()          # /app
SRC_DIR = os.path.join(REPO_ROOT, "src")

ARTIFACT_R = os.path.join(SRC_DIR, "R_sparse.pkl")
ARTIFACT_PRODUCTS = os.path.join(SRC_DIR, "product_ids.pkl")
ARTIFACT_MAP = os.path.join(SRC_DIR, "prod_to_idx.pkl")

# --------------------------------------------------
# Page config
# --------------------------------------------------
st.set_page_config(
    page_title="Amazon Electronics Recommender",
    page_icon="🛒",
    layout="wide"
)

st.title("🛒 Amazon Electronics Product Recommender")
st.caption(
    "Item-based Collaborative Filtering "
    "(Sparse User–Item Matrix + Cosine Similarity)"
)

# --------------------------------------------------
# Load artifacts
# --------------------------------------------------
@st.cache_resource
def load_artifacts():
    required = [ARTIFACT_R, ARTIFACT_PRODUCTS, ARTIFACT_MAP]
    missing = [p for p in required if not os.path.exists(p)]

    if missing:
        raise FileNotFoundError(
            f"Missing files: {missing}\n\n"
            f"Repo root files: {os.listdir(REPO_ROOT)}\n"
            f"src/ files: {os.listdir(SRC_DIR)}"
        )

    R = joblib.load(ARTIFACT_R)                 # scipy.sparse csr_matrix
    product_ids = joblib.load(ARTIFACT_PRODUCTS)
    prod_to_idx = joblib.load(ARTIFACT_MAP)

    product_ids = np.array(list(product_ids))
    return R, product_ids, prod_to_idx

# --------------------------------------------------
# Recommendation function
# --------------------------------------------------
def recommend_sparse(
    R,
    product_ids,
    prod_to_idx,
    product_id: str,
    top_n: int = 10,
    min_sim: float = 0.01
):
    if product_id not in prod_to_idx:
        return pd.DataFrame(
            {"message": ["Product not found. Please try another product_id."]}
        )

    j = prod_to_idx[product_id]

    # item vector (1 x users)
    item_vec = R[:, j].T

    # similarity to all items
    sims = cosine_similarity(item_vec, R.T).ravel()

    # remove self similarity
    sims[j] = -1.0

    valid = np.where(sims >= float(min_sim))[0]
    if valid.size == 0:
        return pd.DataFrame(
            {"message": [f"No recommendations found with min_sim ≥ {min_sim}."]}
        )

    top_idx = valid[np.argsort(sims[valid])[::-1][:top_n]]

    return pd.DataFrame({
        "recommended_product_id": product_ids[top_idx],
        "similarity": sims[top_idx].astype(float)
    })

# --------------------------------------------------
# Sidebar
# --------------------------------------------------
st.sidebar.header("⚙️ Settings")

try:
    R, product_ids, prod_to_idx = load_artifacts()
    st.sidebar.success("Artifacts loaded successfully.")
except Exception as e:
    st.sidebar.error("Artifacts could not be loaded.")
    st.error(str(e))
    st.stop()

st.sidebar.write("**Dataset scope (reduced subset):**")
st.sidebar.write(f"- Users: **{R.shape[0]:,}**")
st.sidebar.write(f"- Products: **{R.shape[1]:,}**")
st.sidebar.write(f"- Interactions: **{R.nnz:,}**")

top_n = st.sidebar.slider(
    "Top-N recommendations",
    min_value=3,
    max_value=30,
    value=10,
    step=1
)

min_sim = st.sidebar.slider(
    "Minimum similarity threshold",
    min_value=0.0,
    max_value=0.20,
    value=0.01,
    step=0.01
)

st.divider()

# --------------------------------------------------
# Main UI
# --------------------------------------------------
col1, col2 = st.columns([2, 1], gap="large")

with col1:
    st.subheader("🔎 Find similar products")
    product_id = st.text_input(
        "Enter a product_id (ASIN)",
        placeholder="e.g. B00005N5PF"
    )

    if st.button("Recommend", type="primary", use_container_width=True):
        product_id = product_id.strip()
        if not product_id:
            st.warning("Please enter a product_id.")
        else:
            with st.spinner("Computing recommendations..."):
                recs = recommend_sparse(
                    R, product_ids, prod_to_idx,
                    product_id, top_n=top_n, min_sim=min_sim
                )

            if "message" in recs.columns:
                st.info(recs["message"].iloc[0])
            else:
                st.success(f"Recommendations for **{product_id}**")
                st.dataframe(recs, use_container_width=True)

with col2:
    st.subheader("🧪 Quick test")
    st.write("Try a random product_id from the dataset:")

    if st.button("Pick random product_id", use_container_width=True):
        st.session_state["random_pid"] = random.choice(product_ids.tolist())

    if "random_pid" in st.session_state:
        st.code(st.session_state["random_pid"])
        if st.button("Recommend for random product_id", use_container_width=True):
            pid = st.session_state["random_pid"]
            with st.spinner("Computing recommendations..."):
                recs = recommend_sparse(
                    R, product_ids, prod_to_idx,
                    pid, top_n=top_n, min_sim=min_sim
                )

            if "message" in recs.columns:
                st.info(recs["message"].iloc[0])
            else:
                st.success(f"Recommendations for **{pid}**")
                st.dataframe(recs, use_container_width=True)

st.divider()
st.caption(
    "Note: This demo uses a reduced subset of the original dataset "
    "(top 4,000 products and 200,000 most active users). "
    "Cosine similarity is computed on-the-fly using a sparse matrix."
)