masadonline commited on
Commit
cc16aeb
Β·
verified Β·
1 Parent(s): 4859885

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -48
app.py CHANGED
@@ -13,14 +13,6 @@ from groq import Groq
13
  import PyPDF2
14
  import requests
15
 
16
- # --- Session State Initialization ---
17
- if 'is_running' not in st.session_state:
18
- st.session_state.is_running = False
19
- if 'log' not in st.session_state:
20
- st.session_state.log = []
21
- if 'stop_event' not in st.session_state:
22
- st.session_state.stop_event = threading.Event()
23
-
24
  # --- Text Extraction Utilities ---
25
  def extract_text_from_pdf(pdf_path):
26
  try:
@@ -122,7 +114,6 @@ def send_twilio_message(client, conversation_sid, body):
122
  )
123
 
124
  # --- Load Knowledge Base ---
125
- @st.cache_resource
126
  def setup_knowledge_base():
127
  folder_path = "docs"
128
  all_text = ""
@@ -141,57 +132,52 @@ def setup_knowledge_base():
141
  index.add(np.array(embeddings).astype('float32'))
142
  return index, model, chunks
143
 
144
- # --- Conversation Monitor ---
145
  def start_conversation_monitor(client, index, embed_model, text_chunks):
146
  last_msg_index = {}
147
 
148
- def poll():
149
- while not st.session_state.stop_event.is_set():
150
- sids = get_whatsapp_conversation_sids(client)
151
- for convo_sid in sids:
152
- try:
153
- question, sender, msg_index = fetch_latest_incoming_message(client, convo_sid)
154
- if question and (convo_sid not in last_msg_index or msg_index > last_msg_index[convo_sid]):
155
- last_msg_index[convo_sid] = msg_index
156
- context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
157
- answer = generate_answer_with_groq(question, context)
158
- send_twilio_message(client, convo_sid, answer)
159
- log_entry = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] SID: {convo_sid} | πŸ“₯: {question} | πŸ“€: {answer}"
160
- st.session_state.log.append(log_entry)
161
- except Exception as e:
162
- st.session_state.log.append(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ❌ Error in SID {convo_sid}: {e}")
163
- time.sleep(5)
164
-
165
- thread = threading.Thread(target=poll, daemon=True)
166
- thread.start()
167
 
168
  # --- Streamlit UI ---
169
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
170
  st.title("πŸ“± Quasa – A Smart WhatsApp Chatbot")
171
 
172
- account_sid = st.secrets.get("TWILIO_SID") or st.text_input("Twilio SID")
173
- auth_token = st.secrets.get("TWILIO_TOKEN") or st.text_input("Twilio Token", type="password")
174
- GROQ_API_KEY = st.secrets.get("GROQ_API_KEY") or st.text_input("GROQ API Key", type="password")
 
 
 
 
 
 
175
 
176
  if all([account_sid, auth_token, GROQ_API_KEY]):
177
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
178
  client = Client(account_sid, auth_token)
 
179
 
180
- if st.button("▢️ Start Chatbot") and not st.session_state.is_running:
181
- st.session_state.stop_event.clear()
182
- st.session_state.is_running = True
183
- st.success("πŸ”„ Loading knowledge base and starting monitor...")
184
  index, model, chunks = setup_knowledge_base()
185
  start_conversation_monitor(client, index, model, chunks)
186
- st.success("🟒 Chatbot is now running...")
187
-
188
- if st.button("⏹ Stop Chatbot") and st.session_state.is_running:
189
- st.session_state.stop_event.set()
190
- st.session_state.is_running = False
191
- st.warning("πŸ›‘ Chatbot stopped.")
192
-
193
- st.markdown("### πŸ“‹ Logs")
194
- for entry in reversed(st.session_state.log[-100:]):
195
- st.text(entry)
196
- else:
197
- st.warning("⚠️ Please enter all required credentials.")
 
13
  import PyPDF2
14
  import requests
15
 
 
 
 
 
 
 
 
 
16
  # --- Text Extraction Utilities ---
17
  def extract_text_from_pdf(pdf_path):
18
  try:
 
114
  )
115
 
116
  # --- Load Knowledge Base ---
 
117
  def setup_knowledge_base():
118
  folder_path = "docs"
119
  all_text = ""
 
132
  index.add(np.array(embeddings).astype('float32'))
133
  return index, model, chunks
134
 
135
+ # --- Monitor All Conversations ---
136
  def start_conversation_monitor(client, index, embed_model, text_chunks):
137
  last_msg_index = {}
138
 
139
+ def poll_conversation(convo_sid):
140
+ while True:
141
+ try:
142
+ question, sender, msg_index = fetch_latest_incoming_message(client, convo_sid)
143
+ if question and (convo_sid not in last_msg_index or msg_index > last_msg_index[convo_sid]):
144
+ last_msg_index[convo_sid] = msg_index
145
+ print(f"\nπŸ“₯ New message from {sender} in {convo_sid}: {question}")
146
+ context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
147
+ answer = generate_answer_with_groq(question, context)
148
+ send_twilio_message(client, convo_sid, answer)
149
+ print(f"πŸ“€ Replied to {sender}: {answer}")
150
+ time.sleep(3)
151
+ except Exception as e:
152
+ print(f"❌ Error in convo {convo_sid} polling:", e)
153
+ time.sleep(5)
154
+
155
+ for sid in get_whatsapp_conversation_sids(client):
156
+ threading.Thread(target=poll_conversation, args=(sid,), daemon=True).start()
 
157
 
158
  # --- Streamlit UI ---
159
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
160
  st.title("πŸ“± Quasa – A Smart WhatsApp Chatbot")
161
 
162
+ account_sid = st.secrets.get("TWILIO_SID")
163
+ auth_token = st.secrets.get("TWILIO_TOKEN")
164
+ GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
165
+
166
+ if not all([account_sid, auth_token, GROQ_API_KEY]):
167
+ st.warning("⚠️ Provide all credentials below:")
168
+ account_sid = st.text_input("Twilio SID", value=account_sid or "")
169
+ auth_token = st.text_input("Twilio Token", type="password", value=auth_token or "")
170
+ GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
171
 
172
  if all([account_sid, auth_token, GROQ_API_KEY]):
173
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
174
  client = Client(account_sid, auth_token)
175
+ conversation_sids = get_whatsapp_conversation_sids(client)
176
 
177
+ if conversation_sids:
178
+ st.success(f"βœ… {len(conversation_sids)} WhatsApp conversation(s) found. Initializing chatbot...")
 
 
179
  index, model, chunks = setup_knowledge_base()
180
  start_conversation_monitor(client, index, model, chunks)
181
+ st.success("🟒 Chatbot is running in background and will reply to new messages.")
182
+ else:
183
+ st.error("❌ No WhatsApp conversations found.")