File size: 11,778 Bytes
f4e7b4f
c832d1c
 
 
9590248
 
 
 
c832d1c
9590248
 
d186b8d
9590248
c832d1c
 
d85b86d
9590248
 
 
f4e7b4f
c832d1c
d85b86d
0a4a544
c9d8fa5
7a5db40
e9f402a
c832d1c
 
 
06b05f8
 
7a5db40
 
06b05f8
c832d1c
7a5db40
c832d1c
 
f4e7b4f
c832d1c
 
 
7a5db40
c832d1c
 
 
 
7a5db40
c832d1c
7a5db40
 
f4e7b4f
9590248
06b05f8
9590248
 
7a5db40
 
06b05f8
 
e9f402a
7a5db40
 
 
06b05f8
c832d1c
06b05f8
 
7a5db40
1039466
 
7a5db40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c832d1c
9590248
 
c832d1c
 
7a5db40
 
 
c832d1c
 
 
 
7a5db40
 
9590248
c832d1c
7a5db40
362a50b
d186b8d
06b05f8
 
 
 
 
 
 
7a5db40
 
 
06b05f8
d186b8d
 
 
06b05f8
 
 
7a5db40
 
 
 
 
06b05f8
 
362a50b
9590248
 
 
d186b8d
30db2dc
06b05f8
9590248
 
d85b86d
9590248
 
 
 
06b05f8
8293692
 
 
 
 
 
06b05f8
d85b86d
 
 
 
 
 
 
9ef413c
d85b86d
2092360
0a4a544
06b05f8
 
 
0a4a544
7a5db40
e9f402a
06b05f8
 
 
7a5db40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06b05f8
 
 
 
7a5db40
06b05f8
 
 
 
 
d85b86d
 
 
06b05f8
 
 
 
d85b86d
06b05f8
3e432a3
 
 
 
d85b86d
3e432a3
 
 
d85b86d
3e432a3
 
 
d85b86d
 
3e432a3
d85b86d
 
3e432a3
d85b86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e432a3
d85b86d
 
06b05f8
2092360
06b05f8
d85b86d
35e0afb
 
7a5db40
06b05f8
7a5db40
 
d85b86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import os
import time
import threading
import streamlit as st
from twilio.rest import Client
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer
import faiss
import numpy as np
import docx
from groq import Groq
import requests
from io import StringIO
from pdfminer.high_level import extract_text_to_fp
from pdfminer.layout import LAParams
from twilio.base.exceptions import TwilioRestException  # Add this at the top
import pdfplumber
import datetime
import csv

APP_START_TIME = datetime.datetime.now(datetime.timezone.utc)

os.environ["PYTORCH_JIT"] = "0"

# ---------------- PDF & DOCX & JSON Extraction ----------------
def _extract_tables_from_page(page):
    tables = page.extract_tables()
    formatted_tables = []
    for table in tables:
        formatted_table = []
        for row in table:
            formatted_row = [cell if cell is not None else "" for cell in row]
            formatted_table.append(formatted_row)
        formatted_tables.append(formatted_table)
    return formatted_tables

def extract_text_from_pdf(pdf_path):
    text_output = StringIO()
    all_tables = []
    try:
        with pdfplumber.open(pdf_path) as pdf:
            for page in pdf.pages:
                all_tables.extend(_extract_tables_from_page(page))
                text = page.extract_text()
                if text:
                    text_output.write(text + "\n\n")
    except Exception as e:
        print(f"pdfplumber error: {e}")
        with open(pdf_path, 'rb') as file:
            extract_text_to_fp(file, text_output, laparams=LAParams(), output_type='text')
    return text_output.getvalue(), all_tables

def _format_tables_internal(tables):
    formatted_tables_str = []
    for table in tables:
        with StringIO() as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(table)
            formatted_tables_str.append(csvfile.getvalue())
    return "\n\n".join(formatted_tables_str)

def clean_extracted_text(text):
    return '\n'.join(' '.join(line.strip().split()) for line in text.splitlines() if line.strip())

def extract_text_from_docx(docx_path):
    try:
        doc = docx.Document(docx_path)
        return '\n'.join(para.text for para in doc.paragraphs)
    except:
        return ""

def load_json_data(json_path):
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        if isinstance(data, dict):
            # Flatten dictionary values (avoiding nested structures as strings)
            return "\n".join(f"{key}: {value}" for key, value in data.items() if not isinstance(value, (dict, list)))
        elif isinstance(data, list):
            # Flatten list of dictionaries
            all_items = []
            for item in data:
                if isinstance(item, dict):
                    all_items.append("\n".join(f"{key}: {value}" for key, value in item.items() if not isinstance(value, (dict, list))))
            return "\n\n".join(all_items)
        else:
            return json.dumps(data, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"JSON read error: {e}")
        return ""

# ---------------- Chunking ----------------
def chunk_text(text, tokenizer, chunk_size=128, chunk_overlap=32):
    tokens = tokenizer.tokenize(text)
    chunks = []
    start = 0
    while start < len(tokens):
        end = min(start + chunk_size, len(tokens))
        chunk = tokens[start:end]
        chunks.append(tokenizer.convert_tokens_to_string(chunk))
        if end == len(tokens): break
        start += chunk_size - chunk_overlap
    return chunks

def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
    q_embedding = embed_model.encode(question)
    D, I = index.search(np.array([q_embedding]), k)
    return [text_chunks[i] for i in I[0]]

# ---------------- Groq Answer Generator ----------------
def generate_answer_with_groq(question, context):
    url = "https://api.groq.com/openai/v1/chat/completions"
    api_key = os.environ.get("GROQ_API_KEY")
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    prompt = (
        f"Customer asked: '{question}'\n\n"
        f"Here is the relevant information to help:\n{context}\n\n"
        f"Respond in a friendly and helpful tone as a toy shop support agent, "
        f"addressing the customer by their name if it's available in the context."
    )
    payload = {
        "model": "llama3-8b-8192",
        "messages": [
            {
                "role": "system",
                "content": (
                    "You are ToyBot, a friendly WhatsApp assistant for an online toy shop. "
                    "Help customers with toys, delivery, and returns in a helpful tone. "
                    "When responding, try to find the customer's name in the provided context "
                    "and address them directly. If the context contains order details and status, "
                    "include that information in your response."
                )
            },
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.5,
        "max_tokens": 300,
    }
    response = requests.post(url, headers=headers, json=payload)
    response.raise_for_status()
    return response.json()['choices'][0]['message']['content'].strip()

# --- Twilio Functions ---
def fetch_latest_incoming_message(client, conversation_sid):
    try:
        messages = client.conversations.v1.conversations(conversation_sid).messages.list()
        for msg in reversed(messages):
            if msg.author.startswith("whatsapp:"):
                return {
                    "sid": msg.sid,
                    "body": msg.body,
                    "author": msg.author,
                    "timestamp": msg.date_created,
                }
    except TwilioRestException as e:
        if e.status == 404:
            print(f"Conversation {conversation_sid} not found, skipping...")
        else:
            print(f"Twilio error fetching messages for {conversation_sid}:", e)
    except Exception as e:
        #print(f"Unexpected error in fetch_latest_incoming_message for {conversation_sid}:", e)
        pass

    return None

def send_twilio_message(client, conversation_sid, body):
    return client.conversations.v1.conversations(conversation_sid).messages.create(
        author="system", body=body
    )

# ---------------- Knowledge Base Setup ----------------
def setup_knowledge_base():
    folder_path = "docs"
    all_text = ""

    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if filename.endswith(".pdf"):
            text, tables = extract_text_from_pdf(file_path)
            all_text += clean_extracted_text(text) + "\n"
            all_text += _format_tables_internal(tables) + "\n"
        elif filename.endswith(".docx"):
            text = extract_text_from_docx(file_path)
            all_text += clean_extracted_text(text) + "\n"
        elif filename.endswith(".json"):
            text = load_json_data(file_path)
            all_text += text + "\n"
        elif filename.endswith(".csv"):
            try:
                with open(file_path, newline='', encoding='utf-8') as csvfile:
                    reader = csv.DictReader(csvfile)
                    for row in reader:
                        line = ' | '.join(f"{k}: {v}" for k, v in row.items())
                        all_text += line + "\n"
            except Exception as e:
                print(f"CSV read error: {e}")

    tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
    chunks = chunk_text(all_text, tokenizer)
    model = SentenceTransformer('all-mpnet-base-v2')
    embeddings = model.encode(chunks, show_progress_bar=False)
    dim = embeddings[0].shape[0]
    index = faiss.IndexFlatL2(dim)
    index.add(np.array(embeddings).astype('float32'))
    return index, model, chunks



# --- Monitor Conversations ---
def start_conversation_monitor(client, index, embed_model, text_chunks):
    processed_convos = set()
    last_processed_timestamp = {}

    def poll_conversation(convo_sid):
        while True:
            try:
                latest_msg = fetch_latest_incoming_message(client, convo_sid)
                if latest_msg:
                    msg_time = latest_msg["timestamp"]
                    if convo_sid not in last_processed_timestamp or msg_time > last_processed_timestamp[convo_sid]:
                        last_processed_timestamp[convo_sid] = msg_time
                        question = latest_msg["body"]
                        sender = latest_msg["author"]
                        print(f"\nπŸ“₯ New message from {sender} in {convo_sid}: {question}")
                        context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
                        answer = generate_answer_with_groq(question, context)
                        send_twilio_message(client, convo_sid, answer)
                        print(f"πŸ“€ Replied to {sender}: {answer}")
                time.sleep(3)
            except Exception as e:
                print(f"❌ Error in convo {convo_sid} polling:", e)
                time.sleep(5)

    def poll_new_conversations():
        print("➑️ Monitoring for new WhatsApp conversations...")
        while True:
            try:
                conversations = client.conversations.v1.conversations.list(limit=20)
                for convo in conversations:
                    convo_full = client.conversations.v1.conversations(convo.sid).fetch()
                    if convo.sid not in processed_convos and convo_full.date_created > APP_START_TIME:
                        participants = client.conversations.v1.conversations(convo.sid).participants.list()
                        for p in participants:
                            address = p.messaging_binding.get("address", "") if p.messaging_binding else ""
                            if address.startswith("whatsapp:"):
                                print(f"πŸ†• New WhatsApp convo found: {convo.sid}")
                                processed_convos.add(convo.sid)
                                threading.Thread(target=poll_conversation, args=(convo.sid,), daemon=True).start()
            except Exception as e:
                print("❌ Error polling conversations:", e)
            time.sleep(5)

    # βœ… Launch conversation polling monitor
    threading.Thread(target=poll_new_conversations, daemon=True).start()



# --- Streamlit UI ---
st.set_page_config(page_title="Quasa – Al-Powered WhatsApp Chatbot", layout="wide")
st.title("πŸ“± Quasa – Al-Powered WhatsApp Chatbot")
index, model, chunks = setup_knowledge_base()

st.success("Knowledge base loaded.")
#st.write("Waiting for WhatsApp messages...")
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("⚠️ Provide all credentials below:")
    account_sid = st.text_input("Twilio SID", value=account_sid or "")
    auth_token = st.text_input("Twilio Token", type="password", value=auth_token or "")
    GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")

if all([account_sid, auth_token, GROQ_API_KEY]):
    os.environ["GROQ_API_KEY"] = GROQ_API_KEY
    client = Client(account_sid, auth_token)

    st.success("🟒 Monitoring new WhatsApp conversations...")
    index, model, chunks = setup_knowledge_base()
    threading.Thread(target=start_conversation_monitor, args=(client, index, model, chunks), daemon=True).start()
    st.info("⏳ Waiting for new messages...")