AmazonRecommendation / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
4d2e2f1 verified
Raw History Blame Contribute Delete
5.76 kB
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."
)