pdp / app.py
Muthuraja18's picture
Update app.py
cdcd6e7 verified
raw
history blame
3.6 kB
import streamlit as st
from pymongo import MongoClient, errors
import pandas as pd
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# =========================
# βš™οΈ CONFIGURATION
# =========================
MONGO_URI = "mongodb+srv://muthurajlingam788:[email protected]/?retryWrites=true&w=majority&tls=true"
DB_NAME = "shopping_mall"
COLLECTION_NAME = "customers"
# =========================
# πŸ” CONNECT TO MONGODB
# =========================
def connect_to_mongo():
try:
client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=20000)
client.admin.command("ping") # Test connection
return client
except errors.ServerSelectionTimeoutError as err:
st.error("❌ Could not connect to MongoDB Atlas.")
st.stop()
client = connect_to_mongo()
db = client[DB_NAME]
collection = db[COLLECTION_NAME]
# =========================
# πŸ€– LOAD EMBEDDING MODEL
# =========================
@st.cache_resource
def load_model():
return SentenceTransformer("all-MiniLM-L6-v2")
model = load_model()
# =========================
# 🧠 STREAMLIT INTERFACE
# =========================
st.title("πŸ›οΈ Shopping Mall Customer Management")
menu = st.sidebar.radio("Menu", ["Add Customer", "View Customers", "Ask AI"])
# =========================
# βž• ADD CUSTOMER
# =========================
if menu == "Add Customer":
st.header("Add Customer Details")
name = st.text_input("Name")
age = st.number_input("Age", min_value=0)
gender = st.selectbox("Gender", ["Male", "Female", "Other"])
items = st.text_input("Items Purchased (comma-separated)")
amount = st.number_input("Total Amount Spent (β‚Ή)", min_value=0.0)
if st.button("Submit"):
if name and items:
customer = {
"name": name,
"age": age,
"gender": gender,
"items": [item.strip() for item in items.split(",")],
"amount": amount
}
collection.insert_one(customer)
st.success("βœ… Customer added successfully!")
else:
st.warning("Please enter at least Name and Items.")
# =========================
# πŸ“‹ VIEW CUSTOMERS
# =========================
elif menu == "View Customers":
st.header("Customer List")
data = list(collection.find({}, {"_id": 0})) # Exclude _id
if data:
df = pd.DataFrame(data)
search = st.text_input("Search by Name")
if search:
df = df[df["name"].str.contains(search, case=False)]
st.dataframe(df)
else:
st.info("No customer records found.")
# =========================
# 🧠 AI QUERY ASSISTANT
# =========================
elif menu == "Ask AI":
st.header("🧠 Ask Questions About Customers")
question = st.text_input("Enter your question")
data = list(collection.find({}, {"_id": 0}))
if not data:
st.warning("No data available to query.")
elif question:
context_texts = [
f"{c['name']} is a {c['age']}-year-old {c['gender']} who bought {', '.join(c['items'])} and spent β‚Ή{c['amount']}."
for c in data
]
question_embedding = model.encode([question])
context_embeddings = model.encode(context_texts)
scores = cosine_similarity(question_embedding, context_embeddings)[0]
best_idx = scores.argmax()
response = context_texts[best_idx]
st.write("πŸ“Œ Most Relevant Info:")
st.success(response)