masadonline commited on
Commit
230aa3a
Β·
verified Β·
1 Parent(s): cbc8c9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -12
app.py CHANGED
@@ -131,33 +131,43 @@ def setup_knowledge_base():
131
  index.add(np.array(embeddings).astype('float32'))
132
  return index, model, chunks
133
 
134
- # --- Monitor All Conversations ---
135
  def start_conversation_monitor(client, index, embed_model, text_chunks):
136
  last_msg_index = {}
137
 
138
  def poll_conversation(convo_sid):
139
- while True:
140
  try:
141
  question, sender, msg_index = fetch_latest_incoming_message(client, convo_sid)
142
  if question and (convo_sid not in last_msg_index or msg_index > last_msg_index[convo_sid]):
143
  last_msg_index[convo_sid] = msg_index
144
- print(f"\nπŸ“₯ New message from {sender} in {convo_sid}: {question}")
145
  context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
146
  answer = generate_answer_with_groq(question, context)
147
  send_twilio_message(client, convo_sid, answer)
148
- print(f"πŸ“€ Replied to {sender}: {answer}")
149
  time.sleep(3)
150
  except Exception as e:
151
- print(f"❌ Error in convo {convo_sid} polling:", e)
152
  time.sleep(5)
153
 
154
  for sid in get_whatsapp_conversation_sids(client):
155
  threading.Thread(target=poll_conversation, args=(sid,), daemon=True).start()
156
 
 
 
 
 
157
  # --- Streamlit UI ---
158
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
159
  st.title("πŸ“± Quasa – A Smart WhatsApp Chatbot")
160
 
 
 
 
 
 
 
161
  account_sid = st.secrets.get("TWILIO_SID")
162
  auth_token = st.secrets.get("TWILIO_TOKEN")
163
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
@@ -171,12 +181,24 @@ if not all([account_sid, auth_token, GROQ_API_KEY]):
171
  if all([account_sid, auth_token, GROQ_API_KEY]):
172
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
173
  client = Client(account_sid, auth_token)
174
- conversation_sids = get_whatsapp_conversation_sids(client)
175
 
176
- if conversation_sids:
177
- st.success(f"βœ… {len(conversation_sids)} WhatsApp conversation(s) found. Initializing chatbot...")
178
- index, model, chunks = setup_knowledge_base()
179
- start_conversation_monitor(client, index, model, chunks)
180
- st.success("🟒 Chatbot is running in background and will reply to new messages.")
 
 
 
 
 
 
181
  else:
182
- st.error("❌ No WhatsApp conversations found.")
 
 
 
 
 
 
 
 
131
  index.add(np.array(embeddings).astype('float32'))
132
  return index, model, chunks
133
 
134
+ # --- Conversation Monitor Thread ---
135
  def start_conversation_monitor(client, index, embed_model, text_chunks):
136
  last_msg_index = {}
137
 
138
  def poll_conversation(convo_sid):
139
+ while st.session_state.chatbot_running:
140
  try:
141
  question, sender, msg_index = fetch_latest_incoming_message(client, convo_sid)
142
  if question and (convo_sid not in last_msg_index or msg_index > last_msg_index[convo_sid]):
143
  last_msg_index[convo_sid] = msg_index
144
+ log(f"πŸ“₯ New message from {sender} in {convo_sid}: {question}")
145
  context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
146
  answer = generate_answer_with_groq(question, context)
147
  send_twilio_message(client, convo_sid, answer)
148
+ log(f"πŸ“€ Replied to {sender}: {answer}")
149
  time.sleep(3)
150
  except Exception as e:
151
+ log(f"❌ Error in convo {convo_sid} polling: {e}")
152
  time.sleep(5)
153
 
154
  for sid in get_whatsapp_conversation_sids(client):
155
  threading.Thread(target=poll_conversation, args=(sid,), daemon=True).start()
156
 
157
+ # --- Logging Utility ---
158
+ def log(message):
159
+ st.session_state.logs.append(f"[{time.strftime('%H:%M:%S')}] {message}")
160
+
161
  # --- Streamlit UI ---
162
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
163
  st.title("πŸ“± Quasa – A Smart WhatsApp Chatbot")
164
 
165
+ # Initialize session state
166
+ if "chatbot_running" not in st.session_state:
167
+ st.session_state.chatbot_running = False
168
+ if "logs" not in st.session_state:
169
+ st.session_state.logs = []
170
+
171
  account_sid = st.secrets.get("TWILIO_SID")
172
  auth_token = st.secrets.get("TWILIO_TOKEN")
173
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
 
181
  if all([account_sid, auth_token, GROQ_API_KEY]):
182
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
183
  client = Client(account_sid, auth_token)
 
184
 
185
+ if not st.session_state.chatbot_running:
186
+ if st.button("▢️ Start Chatbot"):
187
+ conversation_sids = get_whatsapp_conversation_sids(client)
188
+ if conversation_sids:
189
+ log(f"βœ… {len(conversation_sids)} conversation(s) found. Loading knowledge base...")
190
+ index, model, chunks = setup_knowledge_base()
191
+ st.session_state.chatbot_running = True
192
+ log("🟒 Chatbot is running and will reply to new WhatsApp messages.")
193
+ start_conversation_monitor(client, index, model, chunks)
194
+ else:
195
+ st.error("❌ No WhatsApp conversations found.")
196
  else:
197
+ if st.button("⏹ Stop Chatbot"):
198
+ st.session_state.chatbot_running = False
199
+ log("πŸ”΄ Chatbot stopped.")
200
+
201
+ # Display logs
202
+ st.subheader("πŸ“‹ Logs")
203
+ for log_entry in st.session_state.logs[-100:]:
204
+ st.text(log_entry)