masadonline commited on
Commit
bce7695
Β·
verified Β·
1 Parent(s): 6e25eb2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -20
app.py CHANGED
@@ -12,6 +12,12 @@ from groq import Groq
12
  import PyPDF2
13
  import requests
14
 
 
 
 
 
 
 
15
  # --- Document Loaders ---
16
  def extract_text_from_pdf(pdf_path):
17
  try:
@@ -97,6 +103,13 @@ def send_twilio_message(account_sid, auth_token, conversation_sid, body):
97
  except Exception as e:
98
  return str(e)
99
 
 
 
 
 
 
 
 
100
  # --- Streamlit UI ---
101
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
102
 
@@ -132,14 +145,14 @@ account_sid = st.secrets.get("TWILIO_SID")
132
  auth_token = st.secrets.get("TWILIO_TOKEN")
133
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
134
 
135
- # Allow user input fallback
136
  if not all([account_sid, auth_token, GROQ_API_KEY]):
137
  st.warning("⚠️ Some secrets are missing. Please provide them manually:")
138
  account_sid = st.text_input("Twilio SID", value=account_sid or "")
139
  auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
140
  GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
141
 
142
- conversation_sid = st.text_input("Enter Twilio Conversation SID", value="")
 
143
 
144
  if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
145
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
@@ -164,26 +177,25 @@ if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
164
 
165
  index, embedding_model, text_chunks = setup_knowledge_base()
166
 
167
- st.success("βœ… Knowledge base ready. Monitoring WhatsApp messages...")
168
 
169
- # Message index tracking
170
  if "last_processed_index" not in st.session_state:
171
  st.session_state.last_processed_index = -1
172
 
173
- if st.button("πŸ” Check for New WhatsApp Query"):
174
- with st.spinner("Checking for new WhatsApp messages..."):
175
- question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
176
-
177
- if question and msg_index != st.session_state.last_processed_index:
178
- st.session_state.last_processed_index = msg_index
179
- st.info(f"πŸ“₯ New question from **{sender}**:\n\n> {question}")
180
- relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
181
- context = "\n\n".join(relevant_chunks)
182
- answer = generate_answer_with_groq(question, context)
183
- send_twilio_message(account_sid, auth_token, conversation_sid, answer)
184
- st.success("πŸ“€ Answer sent back to user on WhatsApp!")
185
- st.markdown(f"### ✨ Answer:\n\n{answer}")
186
- else:
187
- st.warning("No new messages found.")
188
  else:
189
- st.warning("❗ Please provide all required credentials and conversation SID.")
 
12
  import PyPDF2
13
  import requests
14
 
15
+ # --- Auto Refresh ---
16
+ st_autorefresh = st.experimental_rerun # fallback if newer version doesn't have st_autorefresh
17
+ if hasattr(st, "autorefresh"):
18
+ st_autorefresh = st.autorefresh
19
+ st_autorefresh(interval=10000, key="refresh") # every 10 seconds
20
+
21
  # --- Document Loaders ---
22
  def extract_text_from_pdf(pdf_path):
23
  try:
 
103
  except Exception as e:
104
  return str(e)
105
 
106
+ def fetch_latest_conversation_sid(account_sid, auth_token):
107
+ client = Client(account_sid, auth_token)
108
+ conversations = client.conversations.v1.conversations.list(limit=1)
109
+ if conversations:
110
+ return conversations[0].sid
111
+ return ""
112
+
113
  # --- Streamlit UI ---
114
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
115
 
 
145
  auth_token = st.secrets.get("TWILIO_TOKEN")
146
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
147
 
 
148
  if not all([account_sid, auth_token, GROQ_API_KEY]):
149
  st.warning("⚠️ Some secrets are missing. Please provide them manually:")
150
  account_sid = st.text_input("Twilio SID", value=account_sid or "")
151
  auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
152
  GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
153
 
154
+ conversation_sid_input = st.text_input("Enter Twilio Conversation SID (leave blank for latest)", value="")
155
+ conversation_sid = conversation_sid_input or fetch_latest_conversation_sid(account_sid, auth_token)
156
 
157
  if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
158
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
 
177
 
178
  index, embedding_model, text_chunks = setup_knowledge_base()
179
 
180
+ st.success("βœ… Knowledge base ready. Checking WhatsApp messages every 10 seconds...")
181
 
182
+ # Track last message index
183
  if "last_processed_index" not in st.session_state:
184
  st.session_state.last_processed_index = -1
185
 
186
+ question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
187
+
188
+ if question and msg_index != st.session_state.last_processed_index:
189
+ st.session_state.last_processed_index = msg_index
190
+ st.info(f"πŸ“₯ New question from **{sender}**:\n\n> {question}")
191
+ relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
192
+ context = "\n\n".join(relevant_chunks)
193
+ answer = generate_answer_with_groq(question, context)
194
+ send_twilio_message(account_sid, auth_token, conversation_sid, answer)
195
+ st.success("πŸ“€ Answer sent back to user on WhatsApp!")
196
+ st.markdown(f"### ✨ Answer:\n\n{answer}")
197
+ else:
198
+ st.write("πŸ”„ No new message yet... waiting.")
199
+
 
200
  else:
201
+ st.warning("❗ Please provide all required credentials.")