Quasa / app.py
masadonline's picture
Update app.py
e1e01d8 verified
raw
history blame
7.94 kB
import os
import time
import streamlit as st
from twilio.rest import Client
from pdfminer.high_level import extract_text
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer
import faiss
import numpy as np
import docx
from groq import Groq
import PyPDF2
import requests
from streamlit_extras.st_autorefresh import st_autorefresh
# Extract text from PDF with fallback
def extract_text_from_pdf(pdf_path):
try:
text = ""
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page in pdf_reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text
return text
except Exception as e:
st.write(f"Fallback pdfminer extraction: {e}")
return extract_text(pdf_path)
# Extract text from DOCX
def extract_text_from_docx(docx_path):
try:
doc = docx.Document(docx_path)
return '\n'.join(para.text for para in doc.paragraphs)
except Exception as e:
st.write(f"Docx extraction error: {e}")
return ""
# Chunk text based on tokens
def chunk_text(text, tokenizer, chunk_size=150, chunk_overlap=30):
tokens = tokenizer.tokenize(text)
chunks, start = [], 0
while start < len(tokens):
end = min(start + chunk_size, len(tokens))
chunk_tokens = tokens[start:end]
chunks.append(tokenizer.convert_tokens_to_string(chunk_tokens))
start += chunk_size - chunk_overlap
return chunks
# Retrieve relevant chunks from index
def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
question_embedding = embed_model.encode([question])[0]
D, I = index.search(np.array([question_embedding]).astype('float32'), k)
return [text_chunks[i] for i in I[0]]
# Generate answer using Groq API with retries and timeout
def generate_answer_with_groq(question, context, retries=3, delay=2):
url = "https://api.groq.com/openai/v1/chat/completions"
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
return "⚠️ GROQ_API_KEY not set."
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
prompt = (
f"Customer asked: '{question}'\n\n"
f"Here is the relevant product or policy info to help:\n{context}\n\n"
f"Respond in a friendly and helpful tone as a toy shop support agent."
)
payload = {
"model": "llama3-8b-8192",
"messages": [
{
"role": "system",
"content": (
"You are ToyBot, a friendly and helpful WhatsApp assistant for an online toy shop. "
"Your goal is to politely answer customer questions, help them choose the right toys, "
"provide order or delivery information, explain return policies, and guide them through purchases. "
"Always sound warm, helpful, and trustworthy like a professional customer support agent."
)
},
{"role": "user", "content": prompt},
],
"temperature": 0.5,
"max_tokens": 300,
}
for attempt in range(retries):
try:
response = requests.post(url, headers=headers, json=payload, timeout=10)
response.raise_for_status()
result = response.json()
return result['choices'][0]['message']['content'].strip()
except requests.exceptions.HTTPError as e:
if response.status_code == 503 and attempt < retries - 1:
time.sleep(delay)
continue
else:
return f"⚠️ Groq API HTTPError: {e}"
except Exception as e:
return f"⚠️ Groq API Error: {e}"
# Twilio message fetch and send
def fetch_latest_incoming_message(account_sid, auth_token, conversation_sid):
client = Client(account_sid, auth_token)
messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=10)
for msg in reversed(messages):
if msg.author.startswith("whatsapp:"):
return msg.body, msg.author, msg.index
return None, None, None
def send_twilio_message(account_sid, auth_token, conversation_sid, body):
try:
client = Client(account_sid, auth_token)
message = client.conversations.v1.conversations(conversation_sid).messages.create(author="system", body=body)
return message.sid
except Exception as e:
return str(e)
# Streamlit UI
st.set_page_config(page_title="Quasa – A Smart WhatsApp Chatbot", layout="wide")
st.title("πŸ“± Quasa – A Smart WhatsApp Chatbot")
if "last_index" not in st.session_state:
st.session_state.last_index = -1
account_sid = st.secrets.get("TWILIO_SID")
auth_token = st.secrets.get("TWILIO_TOKEN")
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
if not all([account_sid, auth_token, GROQ_API_KEY]):
st.warning("⚠️ Some secrets not found. Please enter missing credentials below:")
account_sid = st.text_input("Twilio SID", value=account_sid or "")
auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
conversation_sid = st.text_input("Enter Conversation SID", value="")
enable_autorefresh = st.checkbox("πŸ”„ Enable Auto-Refresh", value=True)
interval_seconds = st.selectbox("Refresh Interval (seconds)", options=[5, 10, 15, 30, 60], index=1)
if enable_autorefresh:
st_autorefresh(interval=interval_seconds * 1000, key="auto-refresh")
if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
@st.cache_data(show_spinner=False)
def setup_knowledge_base():
folder_path = "docs"
all_text = ""
try:
for file in os.listdir(folder_path):
if file.endswith(".pdf"):
all_text += extract_text_from_pdf(os.path.join(folder_path, file)) + "\n"
elif file.endswith((".docx", ".doc")):
all_text += extract_text_from_docx(os.path.join(folder_path, file)) + "\n"
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
chunks = chunk_text(all_text, tokenizer)
model = SentenceTransformer('all-mpnet-base-v2')
embeddings = model.encode(chunks)
dim = embeddings[0].shape[0]
index = faiss.IndexFlatL2(dim)
index.add(np.array(embeddings).astype('float32'))
return index, model, chunks
except Exception as e:
st.error(f"Error setting up knowledge base: {e}")
return None, None, None
index, embedding_model, text_chunks = setup_knowledge_base()
if index is None:
st.stop()
st.success("βœ… Knowledge base ready. Monitoring WhatsApp...")
with st.spinner("⏳ Checking for new WhatsApp messages..."):
question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
if question and msg_index > st.session_state.last_index:
st.session_state.last_index = msg_index
st.info(f"πŸ“₯ New Question from {sender}:\n\n> {question}")
relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
context = "\n\n".join(relevant_chunks)
answer = generate_answer_with_groq(question, context)
send_twilio_message(account_sid, auth_token, conversation_sid, answer)
st.success("πŸ“€ Answer sent via WhatsApp!")
st.markdown(f"### ✨ Answer:\n\n{answer}")
else:
st.caption("βœ… No new message yet. Waiting for refresh...")
else:
st.warning("❗ Please provide all required credentials and conversation SID.")