Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,7 +13,7 @@ import PyPDF2
|
|
13 |
import requests
|
14 |
from streamlit_autorefresh import st_autorefresh
|
15 |
|
16 |
-
#
|
17 |
def extract_text_from_pdf(pdf_path):
|
18 |
try:
|
19 |
text = ""
|
@@ -98,23 +98,30 @@ def generate_answer_with_groq(question, context, retries=3, delay=2):
|
|
98 |
except Exception as e:
|
99 |
return f"β οΈ Groq API Error: {e}"
|
100 |
|
101 |
-
def fetch_latest_incoming_message(
|
102 |
-
client = Client(account_sid, auth_token)
|
103 |
messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
|
104 |
for msg in reversed(messages):
|
105 |
if msg.author.startswith("whatsapp:"):
|
106 |
return msg.body, msg.author, msg.index
|
107 |
return None, None, None
|
108 |
|
109 |
-
def send_twilio_message(
|
110 |
try:
|
111 |
-
client = Client(account_sid, auth_token)
|
112 |
message = client.conversations.v1.conversations(conversation_sid).messages.create(author="system", body=body)
|
113 |
return message.sid
|
114 |
except Exception as e:
|
115 |
return str(e)
|
116 |
|
117 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
st.set_page_config(page_title="Quasa β A Smart WhatsApp Chatbot", layout="wide")
|
119 |
st.title("π± Quasa β A Smart WhatsApp Chatbot")
|
120 |
|
@@ -124,17 +131,27 @@ if "last_index" not in st.session_state:
|
|
124 |
account_sid = st.secrets.get("TWILIO_SID")
|
125 |
auth_token = st.secrets.get("TWILIO_TOKEN")
|
126 |
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
127 |
-
conversation_sid = st.secrets.get("TWILIO_CONVERSATION_SID")
|
128 |
|
129 |
-
if not all([account_sid, auth_token, GROQ_API_KEY
|
130 |
st.warning("β οΈ Some secrets not found. Please enter missing credentials below:")
|
131 |
account_sid = st.text_input("Twilio SID", value=account_sid or "")
|
132 |
auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
|
133 |
GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
|
134 |
-
conversation_sid = st.text_input("Twilio Conversation SID", value=conversation_sid or "")
|
135 |
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
|
139 |
@st.cache_data(show_spinner=False)
|
140 |
def setup_knowledge_base():
|
@@ -158,31 +175,24 @@ if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
|
|
158 |
st.error(f"Error setting up knowledge base: {e}")
|
159 |
return None, None, None
|
160 |
|
161 |
-
st.info("π Loading knowledge base...")
|
162 |
index, embedding_model, text_chunks = setup_knowledge_base()
|
163 |
-
|
164 |
if index is None:
|
165 |
st.stop()
|
166 |
|
167 |
st.success("β
Knowledge base ready. Monitoring WhatsApp...")
|
168 |
|
169 |
-
enable_autorefresh = st.checkbox("π Enable Auto-Refresh", value=True)
|
170 |
-
interval_seconds = st.selectbox("Refresh Interval (seconds)", options=[5, 10, 15, 30, 60], index=4)
|
171 |
-
if enable_autorefresh:
|
172 |
-
st_autorefresh(interval=interval_seconds * 1000, key="auto-refresh")
|
173 |
-
|
174 |
with st.spinner("β³ Checking for new WhatsApp messages..."):
|
175 |
-
question, sender, msg_index = fetch_latest_incoming_message(
|
176 |
if question and msg_index > st.session_state.last_index:
|
177 |
st.session_state.last_index = msg_index
|
178 |
st.info(f"π₯ New Question from {sender}:\n\n> {question}")
|
179 |
relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
|
180 |
context = "\n\n".join(relevant_chunks)
|
181 |
answer = generate_answer_with_groq(question, context)
|
182 |
-
send_twilio_message(
|
183 |
st.success("π€ Answer sent via WhatsApp!")
|
184 |
st.markdown(f"### β¨ Answer:\n\n{answer}")
|
185 |
else:
|
186 |
st.caption("β
No new message yet. Waiting for refresh...")
|
187 |
else:
|
188 |
-
st.warning("β Please provide all required credentials
|
|
|
13 |
import requests
|
14 |
from streamlit_autorefresh import st_autorefresh
|
15 |
|
16 |
+
# Extract text from PDF
|
17 |
def extract_text_from_pdf(pdf_path):
|
18 |
try:
|
19 |
text = ""
|
|
|
98 |
except Exception as e:
|
99 |
return f"β οΈ Groq API Error: {e}"
|
100 |
|
101 |
+
def fetch_latest_incoming_message(client, conversation_sid):
|
|
|
102 |
messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
|
103 |
for msg in reversed(messages):
|
104 |
if msg.author.startswith("whatsapp:"):
|
105 |
return msg.body, msg.author, msg.index
|
106 |
return None, None, None
|
107 |
|
108 |
+
def send_twilio_message(client, conversation_sid, body):
|
109 |
try:
|
|
|
110 |
message = client.conversations.v1.conversations(conversation_sid).messages.create(author="system", body=body)
|
111 |
return message.sid
|
112 |
except Exception as e:
|
113 |
return str(e)
|
114 |
|
115 |
+
# Automatically get the latest WhatsApp conversation SID
|
116 |
+
def get_latest_whatsapp_conversation_sid(client):
|
117 |
+
conversations = client.conversations.v1.conversations.list(limit=20)
|
118 |
+
for convo in conversations:
|
119 |
+
if convo.chat_service_sid and "whatsapp" in convo.friendly_name.lower():
|
120 |
+
return convo.sid
|
121 |
+
# fallback to the first available conversation
|
122 |
+
return conversations[0].sid if conversations else None
|
123 |
+
|
124 |
+
# Streamlit UI
|
125 |
st.set_page_config(page_title="Quasa β A Smart WhatsApp Chatbot", layout="wide")
|
126 |
st.title("π± Quasa β A Smart WhatsApp Chatbot")
|
127 |
|
|
|
131 |
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 |
+
if not all([account_sid, auth_token, GROQ_API_KEY]):
|
136 |
st.warning("β οΈ Some secrets not found. Please enter missing credentials below:")
|
137 |
account_sid = st.text_input("Twilio SID", value=account_sid or "")
|
138 |
auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
|
139 |
GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
|
|
|
140 |
|
141 |
+
enable_autorefresh = st.checkbox("π Enable Auto-Refresh", value=True)
|
142 |
+
interval_seconds = st.selectbox("Refresh Interval (seconds)", options=[5, 10, 15, 30, 60], index=4)
|
143 |
+
|
144 |
+
if enable_autorefresh:
|
145 |
+
st_autorefresh(interval=interval_seconds * 1000, key="auto-refresh")
|
146 |
+
|
147 |
+
if all([account_sid, auth_token, GROQ_API_KEY]):
|
148 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
149 |
+
client = Client(account_sid, auth_token)
|
150 |
+
conversation_sid = get_latest_whatsapp_conversation_sid(client)
|
151 |
+
|
152 |
+
if conversation_sid is None:
|
153 |
+
st.error("β No WhatsApp conversation found.")
|
154 |
+
st.stop()
|
155 |
|
156 |
@st.cache_data(show_spinner=False)
|
157 |
def setup_knowledge_base():
|
|
|
175 |
st.error(f"Error setting up knowledge base: {e}")
|
176 |
return None, None, None
|
177 |
|
|
|
178 |
index, embedding_model, text_chunks = setup_knowledge_base()
|
|
|
179 |
if index is None:
|
180 |
st.stop()
|
181 |
|
182 |
st.success("β
Knowledge base ready. Monitoring WhatsApp...")
|
183 |
|
|
|
|
|
|
|
|
|
|
|
184 |
with st.spinner("β³ Checking for new WhatsApp messages..."):
|
185 |
+
question, sender, msg_index = fetch_latest_incoming_message(client, conversation_sid)
|
186 |
if question and msg_index > st.session_state.last_index:
|
187 |
st.session_state.last_index = msg_index
|
188 |
st.info(f"π₯ New Question from {sender}:\n\n> {question}")
|
189 |
relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
|
190 |
context = "\n\n".join(relevant_chunks)
|
191 |
answer = generate_answer_with_groq(question, context)
|
192 |
+
send_twilio_message(client, conversation_sid, answer)
|
193 |
st.success("π€ Answer sent via WhatsApp!")
|
194 |
st.markdown(f"### β¨ Answer:\n\n{answer}")
|
195 |
else:
|
196 |
st.caption("β
No new message yet. Waiting for refresh...")
|
197 |
else:
|
198 |
+
st.warning("β Please provide all required credentials.")
|