masadonline commited on
Commit
2ed8220
Β·
verified Β·
1 Parent(s): 0739925

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -63
app.py CHANGED
@@ -99,8 +99,17 @@ def generate_answer_with_groq(question, context, retries=3, delay=2):
99
  else:
100
  return f"⚠️ Groq API Error: {str(e)}"
101
 
102
-
103
  # --- Twilio Chat Handlers ---
 
 
 
 
 
 
 
 
 
 
104
  def fetch_latest_incoming_message(account_sid, auth_token, conversation_sid):
105
  client = Client(account_sid, auth_token)
106
  messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
@@ -120,88 +129,78 @@ def send_twilio_message(account_sid, auth_token, conversation_sid, body):
120
  # --- Streamlit UI ---
121
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
122
 
123
- # Styling
124
  st.markdown("""
125
  <style>
126
- .big-font {
127
- font-size: 28px !important;
128
- font-weight: bold;
129
- }
130
- .small-font {
131
- font-size: 16px !important;
132
- color: #555;
133
- }
134
  .stButton > button {
135
- background-color: #0066CC;
136
- color: white;
137
- padding: 0.5em 1em;
138
- border-radius: 8px;
139
- font-size: 18px;
140
- }
141
- .stTextInput > div > input {
142
- font-size: 16px;
143
  }
 
144
  </style>
145
  """, unsafe_allow_html=True)
146
 
147
  st.markdown('<div class="big-font">πŸ“± Quasa – A Smart WhatsApp Chatbot</div>', unsafe_allow_html=True)
148
  st.markdown('<div class="small-font">Talk to your documents using WhatsApp. Powered by Groq, Twilio, and RAG.</div>', unsafe_allow_html=True)
149
 
150
- # Load secrets
151
  account_sid = st.secrets.get("TWILIO_SID")
152
  auth_token = st.secrets.get("TWILIO_TOKEN")
153
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
154
 
155
- # Allow user input fallback
156
  if not all([account_sid, auth_token, GROQ_API_KEY]):
157
  st.warning("⚠️ Some secrets are missing. Please provide them manually:")
158
  account_sid = st.text_input("Twilio SID", value=account_sid or "")
159
  auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
160
  GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
161
 
162
- conversation_sid = st.text_input("Enter Twilio Conversation SID", value="")
163
-
164
- if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
165
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
166
 
167
- @st.cache_resource
168
- def setup_knowledge_base():
169
- folder_path = "docs"
170
- all_text = ""
171
- for file in os.listdir(folder_path):
172
- if file.endswith(".pdf"):
173
- all_text += extract_text_from_pdf(os.path.join(folder_path, file)) + "\n"
174
- elif file.endswith((".docx", ".doc")):
175
- all_text += extract_text_from_docx(os.path.join(folder_path, file)) + "\n"
176
- tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
177
- chunks = chunk_text(all_text, tokenizer)
178
- model = SentenceTransformer('all-mpnet-base-v2')
179
- embeddings = model.encode(chunks)
180
- dim = embeddings[0].shape[0]
181
- index = faiss.IndexFlatL2(dim)
182
- index.add(np.array(embeddings))
183
- return index, model, chunks
184
-
185
- index, embedding_model, text_chunks = setup_knowledge_base()
186
-
187
- st.success("βœ… Knowledge base ready. Monitoring WhatsApp messages...")
188
-
189
- if "last_processed_index" not in st.session_state:
190
- st.session_state.last_processed_index = -1
191
-
192
- with st.spinner("Checking for new WhatsApp messages..."):
193
- question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
194
-
195
- if question and msg_index != st.session_state.last_processed_index:
196
- st.session_state.last_processed_index = msg_index
197
- st.info(f"πŸ“₯ New question from **{sender}**:\n\n> {question}")
198
- relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
199
- context = "\n\n".join(relevant_chunks)
200
- answer = generate_answer_with_groq(question, context)
201
- send_twilio_message(account_sid, auth_token, conversation_sid, answer)
202
- st.success("πŸ“€ Answer sent back to user on WhatsApp!")
203
- st.markdown(f"### ✨ Answer:\n\n{answer}")
204
- else:
205
- st.warning("No new messages found.")
 
 
 
 
 
206
  else:
207
- st.warning("❗ Please provide all required credentials and conversation SID.")
 
99
  else:
100
  return f"⚠️ Groq API Error: {str(e)}"
101
 
 
102
  # --- Twilio Chat Handlers ---
103
+ def fetch_latest_conversation_sid(account_sid, auth_token):
104
+ try:
105
+ client = Client(account_sid, auth_token)
106
+ conversations = client.conversations.v1.conversations.list(limit=1)
107
+ if conversations:
108
+ return conversations[0].sid
109
+ except Exception as e:
110
+ st.error(f"⚠️ Could not fetch conversation SID: {e}")
111
+ return None
112
+
113
  def fetch_latest_incoming_message(account_sid, auth_token, conversation_sid):
114
  client = Client(account_sid, auth_token)
115
  messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
 
129
  # --- Streamlit UI ---
130
  st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
131
 
 
132
  st.markdown("""
133
  <style>
134
+ .big-font { font-size: 28px !important; font-weight: bold; }
135
+ .small-font { font-size: 16px; color: #555; }
 
 
 
 
 
 
136
  .stButton > button {
137
+ background-color: #0066CC; color: white;
138
+ padding: 0.5em 1em; border-radius: 8px; font-size: 18px;
 
 
 
 
 
 
139
  }
140
+ .stTextInput > div > input { font-size: 16px; }
141
  </style>
142
  """, unsafe_allow_html=True)
143
 
144
  st.markdown('<div class="big-font">πŸ“± Quasa – A Smart WhatsApp Chatbot</div>', unsafe_allow_html=True)
145
  st.markdown('<div class="small-font">Talk to your documents using WhatsApp. Powered by Groq, Twilio, and RAG.</div>', unsafe_allow_html=True)
146
 
147
+ # Load secrets or fallback
148
  account_sid = st.secrets.get("TWILIO_SID")
149
  auth_token = st.secrets.get("TWILIO_TOKEN")
150
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
151
 
 
152
  if not all([account_sid, auth_token, GROQ_API_KEY]):
153
  st.warning("⚠️ Some secrets are missing. Please provide them manually:")
154
  account_sid = st.text_input("Twilio SID", value=account_sid or "")
155
  auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
156
  GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
157
 
158
+ if all([account_sid, auth_token, GROQ_API_KEY]):
 
 
159
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
160
 
161
+ conversation_sid = fetch_latest_conversation_sid(account_sid, auth_token)
162
+
163
+ if conversation_sid:
164
+ @st.cache_resource
165
+ def setup_knowledge_base():
166
+ folder_path = "docs"
167
+ all_text = ""
168
+ for file in os.listdir(folder_path):
169
+ if file.endswith(".pdf"):
170
+ all_text += extract_text_from_pdf(os.path.join(folder_path, file)) + "\n"
171
+ elif file.endswith((".docx", ".doc")):
172
+ all_text += extract_text_from_docx(os.path.join(folder_path, file)) + "\n"
173
+ tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
174
+ chunks = chunk_text(all_text, tokenizer)
175
+ model = SentenceTransformer('all-mpnet-base-v2')
176
+ embeddings = model.encode(chunks)
177
+ dim = embeddings[0].shape[0]
178
+ index = faiss.IndexFlatL2(dim)
179
+ index.add(np.array(embeddings))
180
+ return index, model, chunks
181
+
182
+ index, embedding_model, text_chunks = setup_knowledge_base()
183
+
184
+ st.success(f"βœ… Knowledge base ready. Monitoring WhatsApp messages for conversation: `{conversation_sid}`")
185
+
186
+ if "last_processed_index" not in st.session_state:
187
+ st.session_state.last_processed_index = -1
188
+
189
+ with st.spinner("Checking for new WhatsApp messages..."):
190
+ question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
191
+
192
+ if question and msg_index != st.session_state.last_processed_index:
193
+ st.session_state.last_processed_index = msg_index
194
+ st.info(f"πŸ“₯ New question from **{sender}**:\n\n> {question}")
195
+ relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
196
+ context = "\n\n".join(relevant_chunks)
197
+ answer = generate_answer_with_groq(question, context)
198
+ send_twilio_message(account_sid, auth_token, conversation_sid, answer)
199
+ st.success("πŸ“€ Answer sent back to user on WhatsApp!")
200
+ st.markdown(f"### ✨ Answer:\n\n{answer}")
201
+ else:
202
+ st.warning("No new messages found.")
203
+ else:
204
+ st.warning("❗ No active conversation found.")
205
  else:
206
+ st.warning("❗ Please provide all required credentials.")