Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
135 |
def start_conversation_monitor(client, index, embed_model, text_chunks):
|
136 |
last_msg_index = {}
|
137 |
|
138 |
-
def
|
139 |
-
while st.session_state.
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
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 |
-
|
166 |
-
|
167 |
-
|
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.
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
st.
|
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.")
|
|
|
|