Muthuraja18 commited on
Commit
8f559aa
Β·
verified Β·
1 Parent(s): 8a06caf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -34
app.py CHANGED
@@ -1,28 +1,59 @@
1
  import streamlit as st
2
- from pymongo import MongoClient
3
  import pandas as pd
4
  from sentence_transformers import SentenceTransformer
5
  from sklearn.metrics.pairwise import cosine_similarity
6
 
7
- # Load embedding model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  @st.cache_resource
9
  def load_model():
10
  return SentenceTransformer("all-MiniLM-L6-v2")
11
 
12
  model = load_model()
13
 
14
- # MongoDB connection
15
- MONGO_URI = "mongodb+srv://muthurajlingam788:VHassOJn4N4niYqg@cluster0.vgobnxf.mongodb.net/mydatabase?retryWrites=true&w=majority"
16
- client = MongoClient(MONGO_URI)
17
- db = client["shopping_mall"]
18
- collection = db["customers"]
19
 
20
- # Streamlit UI
21
  st.title("πŸ›οΈ Shopping Mall Customer Management")
22
-
23
  menu = st.sidebar.radio("Menu", ["Add Customer", "View Customers", "Ask AI"])
24
 
25
- # Insert new customer
 
 
 
26
  if menu == "Add Customer":
27
  st.header("Add Customer Details")
28
  name = st.text_input("Name")
@@ -32,20 +63,26 @@ if menu == "Add Customer":
32
  amount = st.number_input("Total Amount Spent (β‚Ή)", min_value=0.0)
33
 
34
  if st.button("Submit"):
35
- customer = {
36
- "name": name,
37
- "age": age,
38
- "gender": gender,
39
- "items": [item.strip() for item in items.split(",")],
40
- "amount": amount
41
- }
42
- collection.insert_one(customer)
43
- st.success("Customer added successfully!")
44
-
45
- # View customers
 
 
 
 
 
 
46
  elif menu == "View Customers":
47
  st.header("Customer List")
48
- data = list(collection.find({}, {"_id": 0})) # Exclude _id field
49
 
50
  if data:
51
  df = pd.DataFrame(data)
@@ -56,23 +93,24 @@ elif menu == "View Customers":
56
  else:
57
  st.info("No customer records found.")
58
 
59
- # AI Query Assistant
 
 
 
60
  elif menu == "Ask AI":
61
  st.header("🧠 Ask Questions About Customers")
62
  question = st.text_input("Enter your question")
63
 
64
- # Load and format data
65
  data = list(collection.find({}, {"_id": 0}))
 
66
  if not data:
67
  st.warning("No data available to query.")
68
- else:
69
- context_texts = []
70
- for c in data:
71
- context_texts.append(
72
- f"{c['name']} is a {c['age']}-year-old {c['gender']} who bought {', '.join(c['items'])} and spent β‚Ή{c['amount']}."
73
- )
74
 
75
- # Encode and search best match
76
  question_embedding = model.encode([question])
77
  context_embeddings = model.encode(context_texts)
78
 
@@ -80,6 +118,5 @@ elif menu == "Ask AI":
80
  best_idx = scores.argmax()
81
  response = context_texts[best_idx]
82
 
83
- if question:
84
- st.write("πŸ“Œ Most Relevant Info:")
85
- st.success(response)
 
1
  import streamlit as st
2
+ from pymongo import MongoClient, errors
3
  import pandas as pd
4
  from sentence_transformers import SentenceTransformer
5
  from sklearn.metrics.pairwise import cosine_similarity
6
 
7
+ # =========================
8
+ # βš™οΈ CONFIGURATION
9
+ # =========================
10
+
11
+ MONGO_URI = (
12
+ "mongodb+srv://muthurajlingam788:VHassOJn4N4niYqg@cluster0.vgobnxf.mongodb.net/"
13
+ "?retryWrites=true&w=majority&tls=true"
14
+ )
15
+
16
+ DB_NAME = "shopping_mall"
17
+ COLLECTION_NAME = "customers"
18
+
19
+ # =========================
20
+ # πŸ” CONNECT TO MONGODB
21
+ # =========================
22
+
23
+ def connect_to_mongo():
24
+ try:
25
+ client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=20000)
26
+ client.admin.command("ping") # Test connection
27
+ return client
28
+ except errors.ServerSelectionTimeoutError as err:
29
+ st.error("❌ Could not connect to MongoDB Atlas.")
30
+ st.stop()
31
+
32
+ client = connect_to_mongo()
33
+ db = client[DB_NAME]
34
+ collection = db[COLLECTION_NAME]
35
+
36
+ # =========================
37
+ # πŸ€– LOAD EMBEDDING MODEL
38
+ # =========================
39
+
40
  @st.cache_resource
41
  def load_model():
42
  return SentenceTransformer("all-MiniLM-L6-v2")
43
 
44
  model = load_model()
45
 
46
+ # =========================
47
+ # 🧠 STREAMLIT INTERFACE
48
+ # =========================
 
 
49
 
 
50
  st.title("πŸ›οΈ Shopping Mall Customer Management")
 
51
  menu = st.sidebar.radio("Menu", ["Add Customer", "View Customers", "Ask AI"])
52
 
53
+ # =========================
54
+ # βž• ADD CUSTOMER
55
+ # =========================
56
+
57
  if menu == "Add Customer":
58
  st.header("Add Customer Details")
59
  name = st.text_input("Name")
 
63
  amount = st.number_input("Total Amount Spent (β‚Ή)", min_value=0.0)
64
 
65
  if st.button("Submit"):
66
+ if name and items:
67
+ customer = {
68
+ "name": name,
69
+ "age": age,
70
+ "gender": gender,
71
+ "items": [item.strip() for item in items.split(",")],
72
+ "amount": amount
73
+ }
74
+ collection.insert_one(customer)
75
+ st.success("βœ… Customer added successfully!")
76
+ else:
77
+ st.warning("Please enter at least Name and Items.")
78
+
79
+ # =========================
80
+ # πŸ“‹ VIEW CUSTOMERS
81
+ # =========================
82
+
83
  elif menu == "View Customers":
84
  st.header("Customer List")
85
+ data = list(collection.find({}, {"_id": 0})) # Exclude _id
86
 
87
  if data:
88
  df = pd.DataFrame(data)
 
93
  else:
94
  st.info("No customer records found.")
95
 
96
+ # =========================
97
+ # 🧠 AI QUERY ASSISTANT
98
+ # =========================
99
+
100
  elif menu == "Ask AI":
101
  st.header("🧠 Ask Questions About Customers")
102
  question = st.text_input("Enter your question")
103
 
 
104
  data = list(collection.find({}, {"_id": 0}))
105
+
106
  if not data:
107
  st.warning("No data available to query.")
108
+ elif question:
109
+ context_texts = [
110
+ f"{c['name']} is a {c['age']}-year-old {c['gender']} who bought {', '.join(c['items'])} and spent β‚Ή{c['amount']}."
111
+ for c in data
112
+ ]
 
113
 
 
114
  question_embedding = model.encode([question])
115
  context_embeddings = model.encode(context_texts)
116
 
 
118
  best_idx = scores.argmax()
119
  response = context_texts[best_idx]
120
 
121
+ st.write("πŸ“Œ Most Relevant Info:")
122
+ st.success(response)