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

Update app.py

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