Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
# ---
|
145 |
def start_conversation_monitor(client, index, embed_model, text_chunks):
|
146 |
last_msg_index = {}
|
147 |
|
148 |
-
def
|
149 |
-
while
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
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")
|
173 |
-
auth_token = st.secrets.get("TWILIO_TOKEN")
|
174 |
-
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
181 |
-
st.
|
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
|
187 |
-
|
188 |
-
|
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.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|