masadonline commited on
Commit
9ef413c
·
verified ·
1 Parent(s): 8293692

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -6
app.py CHANGED
@@ -144,7 +144,6 @@ def send_twilio_message(client, conversation_sid, body):
144
  def get_latest_whatsapp_conversation_sid(client):
145
  try:
146
  conversations = client.conversations.v1.conversations.list(limit=20)
147
- # Filter conversations created after app start time
148
  filtered = [
149
  c for c in conversations
150
  if c.date_created and c.date_created > APP_START_TIME
@@ -157,6 +156,35 @@ def get_latest_whatsapp_conversation_sid(client):
157
  print("Error fetching valid conversation SID:", e)
158
  return None
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  # ---------------- Knowledge Base Setup ----------------
161
  def setup_knowledge_base():
162
  folder = "docs"
@@ -169,6 +197,9 @@ def setup_knowledge_base():
169
  elif f.endswith(".docx"):
170
  text += clean_extracted_text(extract_text_from_docx(path)) + "\n"
171
  elif f.endswith(".json"):
 
 
 
172
  text += load_json_data(path) + "\n"
173
  elif f.endswith(".csv"):
174
  with open(path, newline='', encoding='utf-8') as csvfile:
@@ -185,7 +216,9 @@ def process_messages_loop():
185
  embeddings = embed_model.encode(text_chunks)
186
  index = faiss.IndexFlatL2(embeddings.shape[1])
187
  index.add(embeddings)
188
-
 
 
189
  seen_sids = set()
190
 
191
  while True:
@@ -198,8 +231,14 @@ def process_messages_loop():
198
  if message and message["sid"] not in seen_sids:
199
  seen_sids.add(message["sid"])
200
  question = message["body"]
201
- chunks = retrieve_chunks(question, index, embed_model, text_chunks)
202
- answer = generate_answer_with_groq(question, "\n\n".join(chunks))
 
 
 
 
 
 
203
  send_twilio_message(twilio_client, conversation_sid, answer)
204
 
205
  time.sleep(5)
@@ -208,6 +247,6 @@ def process_messages_loop():
208
  st.title("ToyShop WhatsApp Assistant (Groq + Twilio)")
209
 
210
  if st.button("Start WhatsApp Bot"):
211
- thread = threading.Thread(target=process_messages_loop)
212
  thread.start()
213
- st.success("WhatsApp assistant started and monitoring for new messages.")
 
144
  def get_latest_whatsapp_conversation_sid(client):
145
  try:
146
  conversations = client.conversations.v1.conversations.list(limit=20)
 
147
  filtered = [
148
  c for c in conversations
149
  if c.date_created and c.date_created > APP_START_TIME
 
156
  print("Error fetching valid conversation SID:", e)
157
  return None
158
 
159
+ # ---------------- Load Orders ----------------
160
+ def load_orders():
161
+ orders_path = "docs/orders.json"
162
+ try:
163
+ with open(orders_path, "r", encoding="utf-8") as f:
164
+ return json.load(f)
165
+ except Exception as e:
166
+ print(f"Error loading orders: {e}")
167
+ return {}
168
+
169
+ def extract_order_id(text):
170
+ pattern = r"\bORD\d{3,}\b"
171
+ match = re.search(pattern, text, re.IGNORECASE)
172
+ if match:
173
+ return match.group(0).upper()
174
+ return None
175
+
176
+ def format_order_response(order_id, order_data):
177
+ if not order_data:
178
+ return f"Sorry, I could not find details for order ID {order_id}."
179
+ details = [
180
+ f"Order ID: {order_id}",
181
+ f"Customer Name: {order_data.get('customer_name', 'N/A')}",
182
+ f"Address: {order_data.get('address', 'N/A')}",
183
+ f"Items: {', '.join(order_data.get('items', []))}",
184
+ f"Status: {order_data.get('status', 'N/A')}",
185
+ ]
186
+ return "\n".join(details)
187
+
188
  # ---------------- Knowledge Base Setup ----------------
189
  def setup_knowledge_base():
190
  folder = "docs"
 
197
  elif f.endswith(".docx"):
198
  text += clean_extracted_text(extract_text_from_docx(path)) + "\n"
199
  elif f.endswith(".json"):
200
+ # Skip orders.json here to avoid mixing with KB text
201
+ if f == "orders.json":
202
+ continue
203
  text += load_json_data(path) + "\n"
204
  elif f.endswith(".csv"):
205
  with open(path, newline='', encoding='utf-8') as csvfile:
 
216
  embeddings = embed_model.encode(text_chunks)
217
  index = faiss.IndexFlatL2(embeddings.shape[1])
218
  index.add(embeddings)
219
+
220
+ orders = load_orders() # Load orders once at start
221
+
222
  seen_sids = set()
223
 
224
  while True:
 
231
  if message and message["sid"] not in seen_sids:
232
  seen_sids.add(message["sid"])
233
  question = message["body"]
234
+
235
+ order_id = extract_order_id(question)
236
+ if order_id and order_id in orders:
237
+ answer = format_order_response(order_id, orders[order_id])
238
+ else:
239
+ chunks = retrieve_chunks(question, index, embed_model, text_chunks)
240
+ answer = generate_answer_with_groq(question, "\n\n".join(chunks))
241
+
242
  send_twilio_message(twilio_client, conversation_sid, answer)
243
 
244
  time.sleep(5)
 
247
  st.title("ToyShop WhatsApp Assistant (Groq + Twilio)")
248
 
249
  if st.button("Start WhatsApp Bot"):
250
+ thread = threading.Thread(target=process_messages_loop, daemon=True)
251
  thread.start()
252
+ st.success("WhatsApp assistant started and monitoring for new messages.")