Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
135 |
def start_conversation_monitor(client, index, embed_model, text_chunks):
|
136 |
last_msg_index = {}
|
137 |
|
138 |
def poll_conversation(convo_sid):
|
139 |
-
while
|
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 |
-
|
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 |
-
|
149 |
time.sleep(3)
|
150 |
except Exception as e:
|
151 |
-
|
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
|
177 |
-
st.
|
178 |
-
|
179 |
-
|
180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
else:
|
182 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|