pdp / app.py
Muthuraja18's picture
Update app.py (#15)
66c9867 verified
raw
history blame
2.76 kB
import streamlit as st
from pymongo import MongoClient
import pandas as pd
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# Load embedding model
@st.cache_resource
def load_model():
return SentenceTransformer("all-MiniLM-L6-v2")
model = load_model()
# MongoDB connection
MONGO_URI = "mongodb+srv://muthurajlingam788:VHassOJn4N4niYqg@cluster0.vgobnxf.mongodb.net/mydatabase?retryWrites=true&w=majority"
client = MongoClient(MONGO_URI)
db = client["shopping_mall"]
collection = db["customers"]
# Streamlit UI
st.title("🛍️ Shopping Mall Customer Management")
menu = st.sidebar.radio("Menu", ["Add Customer", "View Customers", "Ask AI"])
# Insert new 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"):
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!")
# View customers
elif menu == "View Customers":
st.header("Customer List")
data = list(collection.find({}, {"_id": 0})) # Exclude _id field
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")
# Load and format data
data = list(collection.find({}, {"_id": 0}))
if not data:
st.warning("No data available to query.")
else:
context_texts = []
for c in data:
context_texts.append(
f"{c['name']} is a {c['age']}-year-old {c['gender']} who bought {', '.join(c['items'])} and spent ₹{c['amount']}."
)
# Encode and search best match
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]
if question:
st.write("📌 Most Relevant Info:")
st.success(response)