Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,108 +13,102 @@ import requests
|
|
13 |
from io import StringIO
|
14 |
from pdfminer.high_level import extract_text_to_fp
|
15 |
from pdfminer.layout import LAParams
|
16 |
-
from twilio.base.exceptions import TwilioRestException
|
17 |
import pdfplumber
|
18 |
import datetime
|
19 |
import csv
|
|
|
|
|
20 |
|
21 |
APP_START_TIME = datetime.datetime.now(datetime.timezone.utc)
|
22 |
-
|
23 |
os.environ["PYTORCH_JIT"] = "0"
|
24 |
|
25 |
-
#
|
26 |
def _extract_tables_from_page(page):
|
27 |
-
"""Extracts tables from a single page of a PDF."""
|
28 |
-
|
29 |
tables = page.extract_tables()
|
30 |
-
if not tables:
|
31 |
-
return []
|
32 |
-
|
33 |
formatted_tables = []
|
34 |
for table in tables:
|
35 |
formatted_table = []
|
36 |
for row in table:
|
37 |
-
if
|
38 |
-
|
39 |
-
formatted_table.append(formatted_row)
|
40 |
-
else:
|
41 |
-
formatted_table.append([""]) # Append an empty row if the row is None
|
42 |
formatted_tables.append(formatted_table)
|
43 |
return formatted_tables
|
44 |
-
|
45 |
def extract_text_from_pdf(pdf_path):
|
46 |
text_output = StringIO()
|
47 |
all_tables = []
|
48 |
try:
|
49 |
with pdfplumber.open(pdf_path) as pdf:
|
50 |
for page in pdf.pages:
|
51 |
-
|
52 |
-
page_tables = _extract_tables_from_page(page)
|
53 |
-
if page_tables:
|
54 |
-
all_tables.extend(page_tables)
|
55 |
-
# Extract text
|
56 |
text = page.extract_text()
|
57 |
if text:
|
58 |
text_output.write(text + "\n\n")
|
59 |
except Exception as e:
|
60 |
-
print(f"
|
61 |
-
# Fallback to pdfminer if pdfplumber fails
|
62 |
with open(pdf_path, 'rb') as file:
|
63 |
-
extract_text_to_fp(file, text_output, laparams=LAParams(), output_type='text'
|
64 |
-
|
65 |
-
return extracted_text, all_tables # Return text and list of tables
|
66 |
-
|
67 |
-
def clean_extracted_text(text):
|
68 |
-
lines = text.splitlines()
|
69 |
-
cleaned = []
|
70 |
-
for line in lines:
|
71 |
-
line = line.strip()
|
72 |
-
if line:
|
73 |
-
line = ' '.join(line.split())
|
74 |
-
cleaned.append(line)
|
75 |
-
return '\n'.join(cleaned)
|
76 |
|
77 |
def _format_tables_internal(tables):
|
78 |
-
"""Formats extracted tables into a string representation."""
|
79 |
-
|
80 |
formatted_tables_str = []
|
81 |
for table in tables:
|
82 |
-
# Use csv writer to handle commas and quotes correctly
|
83 |
with StringIO() as csvfile:
|
84 |
-
|
85 |
-
|
86 |
formatted_tables_str.append(csvfile.getvalue())
|
87 |
return "\n\n".join(formatted_tables_str)
|
88 |
|
89 |
-
|
|
|
|
|
90 |
def extract_text_from_docx(docx_path):
|
91 |
try:
|
92 |
doc = docx.Document(docx_path)
|
93 |
return '\n'.join(para.text for para in doc.paragraphs)
|
94 |
-
except
|
95 |
return ""
|
96 |
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
tokens = tokenizer.tokenize(text)
|
100 |
chunks = []
|
101 |
start = 0
|
102 |
while start < len(tokens):
|
103 |
end = min(start + chunk_size, len(tokens))
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
if end == len(tokens):
|
108 |
-
break
|
109 |
start += chunk_size - chunk_overlap
|
110 |
return chunks
|
111 |
|
112 |
def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
|
113 |
-
|
114 |
-
D, I = index.search(np.array([
|
115 |
return [text_chunks[i] for i in I[0]]
|
116 |
|
117 |
-
#
|
118 |
def generate_answer_with_groq(question, context):
|
119 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
120 |
api_key = os.environ.get("GROQ_API_KEY")
|
@@ -124,8 +118,9 @@ def generate_answer_with_groq(question, context):
|
|
124 |
}
|
125 |
prompt = (
|
126 |
f"Customer asked: '{question}'\n\n"
|
127 |
-
f"Here is the relevant
|
128 |
-
f"Respond in a friendly and helpful tone as a toy shop support agent
|
|
|
129 |
)
|
130 |
payload = {
|
131 |
"model": "llama3-8b-8192",
|
@@ -133,9 +128,11 @@ def generate_answer_with_groq(question, context):
|
|
133 |
{
|
134 |
"role": "system",
|
135 |
"content": (
|
136 |
-
"You are ToyBot, a friendly
|
137 |
-
"
|
138 |
-
"
|
|
|
|
|
139 |
)
|
140 |
},
|
141 |
{"role": "user", "content": prompt},
|
@@ -147,7 +144,7 @@ def generate_answer_with_groq(question, context):
|
|
147 |
response.raise_for_status()
|
148 |
return response.json()['choices'][0]['message']['content'].strip()
|
149 |
|
150 |
-
#
|
151 |
def fetch_latest_incoming_message(client, conversation_sid):
|
152 |
try:
|
153 |
messages = client.conversations.v1.conversations(conversation_sid).messages.list()
|
@@ -160,14 +157,7 @@ def fetch_latest_incoming_message(client, conversation_sid):
|
|
160 |
"timestamp": msg.date_created,
|
161 |
}
|
162 |
except TwilioRestException as e:
|
163 |
-
|
164 |
-
print(f"Conversation {conversation_sid} not found, skipping...")
|
165 |
-
else:
|
166 |
-
print(f"Twilio error fetching messages for {conversation_sid}:", e)
|
167 |
-
except Exception as e:
|
168 |
-
#print(f"Unexpected error in fetch_latest_incoming_message for {conversation_sid}:", e)
|
169 |
-
pass
|
170 |
-
|
171 |
return None
|
172 |
|
173 |
def send_twilio_message(client, conversation_sid, body):
|
@@ -175,121 +165,82 @@ def send_twilio_message(client, conversation_sid, body):
|
|
175 |
author="system", body=body
|
176 |
)
|
177 |
|
178 |
-
#
|
179 |
def setup_knowledge_base():
|
180 |
folder_path = "docs"
|
181 |
all_text = ""
|
182 |
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
try:
|
205 |
-
with open(csv_path, newline='', encoding='utf-8') as csvfile:
|
206 |
-
reader = csv.DictReader(csvfile)
|
207 |
-
for row in reader:
|
208 |
-
line = f"Product ID: {row.get('ProductID')} | Toy Name: {row.get('ToyName')} | Category: {row.get('Category')} | Price(USD): {row.get('Price(USD)')} | Stock Quantity: {row.get('StockQuantity')} | Description: {row.get('Description')}"
|
209 |
-
all_text += line + "\n"
|
210 |
-
except Exception as e:
|
211 |
-
print(f"β Error reading {filename}: {e}")
|
212 |
|
213 |
-
# Tokenization & chunking
|
214 |
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
|
215 |
chunks = chunk_text(all_text, tokenizer)
|
216 |
model = SentenceTransformer('all-mpnet-base-v2')
|
217 |
-
embeddings = model.encode(chunks, show_progress_bar=False
|
218 |
dim = embeddings[0].shape[0]
|
219 |
index = faiss.IndexFlatL2(dim)
|
220 |
index.add(np.array(embeddings).astype('float32'))
|
221 |
return index, model, chunks
|
222 |
|
223 |
-
|
224 |
-
|
225 |
-
# --- Monitor Conversations ---
|
226 |
def start_conversation_monitor(client, index, embed_model, text_chunks):
|
227 |
processed_convos = set()
|
228 |
last_processed_timestamp = {}
|
229 |
|
230 |
-
def
|
231 |
-
while True:
|
232 |
-
try:
|
233 |
-
latest_msg = fetch_latest_incoming_message(client, convo_sid)
|
234 |
-
if latest_msg:
|
235 |
-
msg_time = latest_msg["timestamp"]
|
236 |
-
if convo_sid not in last_processed_timestamp or msg_time > last_processed_timestamp[convo_sid]:
|
237 |
-
last_processed_timestamp[convo_sid] = msg_time
|
238 |
-
question = latest_msg["body"]
|
239 |
-
sender = latest_msg["author"]
|
240 |
-
print(f"\nπ₯ New message from {sender} in {convo_sid}: {question}")
|
241 |
-
context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
|
242 |
-
answer = generate_answer_with_groq(question, context)
|
243 |
-
send_twilio_message(client, convo_sid, answer)
|
244 |
-
print(f"π€ Replied to {sender}: {answer}")
|
245 |
-
time.sleep(3)
|
246 |
-
except Exception as e:
|
247 |
-
print(f"β Error in convo {convo_sid} polling:", e)
|
248 |
-
time.sleep(5)
|
249 |
-
|
250 |
-
def poll_new_conversations():
|
251 |
-
print("β‘οΈ Monitoring for new WhatsApp conversations...")
|
252 |
while True:
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
threading.Thread(target=poll_conversation, args=(convo.sid,), daemon=True).start()
|
265 |
-
except Exception as e:
|
266 |
-
print("β Error polling conversations:", e)
|
267 |
time.sleep(5)
|
268 |
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
|
274 |
-
#
|
275 |
-
|
276 |
-
st.title("
|
|
|
277 |
|
278 |
-
account_sid = st.secrets.get("TWILIO_SID")
|
279 |
-
auth_token = st.secrets.get("TWILIO_TOKEN")
|
280 |
-
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
281 |
-
|
282 |
-
if not all([account_sid, auth_token, GROQ_API_KEY]):
|
283 |
-
st.warning("β οΈ Provide all credentials below:")
|
284 |
-
account_sid = st.text_input("Twilio SID", value=account_sid or "")
|
285 |
-
auth_token = st.text_input("Twilio Token", type="password", value=auth_token or "")
|
286 |
-
GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
|
287 |
-
|
288 |
-
if all([account_sid, auth_token, GROQ_API_KEY]):
|
289 |
-
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
290 |
-
client = Client(account_sid, auth_token)
|
291 |
-
|
292 |
-
st.success("π’ Monitoring new WhatsApp conversations...")
|
293 |
index, model, chunks = setup_knowledge_base()
|
294 |
-
|
295 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
from io import StringIO
|
14 |
from pdfminer.high_level import extract_text_to_fp
|
15 |
from pdfminer.layout import LAParams
|
16 |
+
from twilio.base.exceptions import TwilioRestException
|
17 |
import pdfplumber
|
18 |
import datetime
|
19 |
import csv
|
20 |
+
import json
|
21 |
+
import re
|
22 |
|
23 |
APP_START_TIME = datetime.datetime.now(datetime.timezone.utc)
|
|
|
24 |
os.environ["PYTORCH_JIT"] = "0"
|
25 |
|
26 |
+
# ---------------- PDF & DOCX & JSON Extraction ----------------
|
27 |
def _extract_tables_from_page(page):
|
|
|
|
|
28 |
tables = page.extract_tables()
|
|
|
|
|
|
|
29 |
formatted_tables = []
|
30 |
for table in tables:
|
31 |
formatted_table = []
|
32 |
for row in table:
|
33 |
+
formatted_row = [cell if cell is not None else "" for cell in row]
|
34 |
+
formatted_table.append(formatted_row)
|
|
|
|
|
|
|
35 |
formatted_tables.append(formatted_table)
|
36 |
return formatted_tables
|
37 |
+
|
38 |
def extract_text_from_pdf(pdf_path):
|
39 |
text_output = StringIO()
|
40 |
all_tables = []
|
41 |
try:
|
42 |
with pdfplumber.open(pdf_path) as pdf:
|
43 |
for page in pdf.pages:
|
44 |
+
all_tables.extend(_extract_tables_from_page(page))
|
|
|
|
|
|
|
|
|
45 |
text = page.extract_text()
|
46 |
if text:
|
47 |
text_output.write(text + "\n\n")
|
48 |
except Exception as e:
|
49 |
+
print(f"pdfplumber error: {e}")
|
|
|
50 |
with open(pdf_path, 'rb') as file:
|
51 |
+
extract_text_to_fp(file, text_output, laparams=LAParams(), output_type='text')
|
52 |
+
return text_output.getvalue(), all_tables
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
def _format_tables_internal(tables):
|
|
|
|
|
55 |
formatted_tables_str = []
|
56 |
for table in tables:
|
|
|
57 |
with StringIO() as csvfile:
|
58 |
+
writer = csv.writer(csvfile)
|
59 |
+
writer.writerows(table)
|
60 |
formatted_tables_str.append(csvfile.getvalue())
|
61 |
return "\n\n".join(formatted_tables_str)
|
62 |
|
63 |
+
def clean_extracted_text(text):
|
64 |
+
return '\n'.join(' '.join(line.strip().split()) for line in text.splitlines() if line.strip())
|
65 |
+
|
66 |
def extract_text_from_docx(docx_path):
|
67 |
try:
|
68 |
doc = docx.Document(docx_path)
|
69 |
return '\n'.join(para.text for para in doc.paragraphs)
|
70 |
+
except:
|
71 |
return ""
|
72 |
|
73 |
+
def load_json_data(json_path):
|
74 |
+
try:
|
75 |
+
with open(json_path, 'r', encoding='utf-8') as f:
|
76 |
+
data = json.load(f)
|
77 |
+
if isinstance(data, dict):
|
78 |
+
# Flatten dictionary values (avoiding nested structures as strings)
|
79 |
+
return "\n".join(f"{key}: {value}" for key, value in data.items() if not isinstance(value, (dict, list)))
|
80 |
+
elif isinstance(data, list):
|
81 |
+
# Flatten list of dictionaries
|
82 |
+
all_items = []
|
83 |
+
for item in data:
|
84 |
+
if isinstance(item, dict):
|
85 |
+
all_items.append("\n".join(f"{key}: {value}" for key, value in item.items() if not isinstance(value, (dict, list))))
|
86 |
+
return "\n\n".join(all_items)
|
87 |
+
else:
|
88 |
+
return json.dumps(data, ensure_ascii=False, indent=2)
|
89 |
+
except Exception as e:
|
90 |
+
print(f"JSON read error: {e}")
|
91 |
+
return ""
|
92 |
+
|
93 |
+
# ---------------- Chunking ----------------
|
94 |
+
def chunk_text(text, tokenizer, chunk_size=128, chunk_overlap=32):
|
95 |
tokens = tokenizer.tokenize(text)
|
96 |
chunks = []
|
97 |
start = 0
|
98 |
while start < len(tokens):
|
99 |
end = min(start + chunk_size, len(tokens))
|
100 |
+
chunk = tokens[start:end]
|
101 |
+
chunks.append(tokenizer.convert_tokens_to_string(chunk))
|
102 |
+
if end == len(tokens): break
|
|
|
|
|
103 |
start += chunk_size - chunk_overlap
|
104 |
return chunks
|
105 |
|
106 |
def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
|
107 |
+
q_embedding = embed_model.encode(question)
|
108 |
+
D, I = index.search(np.array([q_embedding]), k)
|
109 |
return [text_chunks[i] for i in I[0]]
|
110 |
|
111 |
+
# ---------------- Groq Answer Generator ----------------
|
112 |
def generate_answer_with_groq(question, context):
|
113 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
114 |
api_key = os.environ.get("GROQ_API_KEY")
|
|
|
118 |
}
|
119 |
prompt = (
|
120 |
f"Customer asked: '{question}'\n\n"
|
121 |
+
f"Here is the relevant information to help:\n{context}\n\n"
|
122 |
+
f"Respond in a friendly and helpful tone as a toy shop support agent, "
|
123 |
+
f"addressing the customer by their name if it's available in the context."
|
124 |
)
|
125 |
payload = {
|
126 |
"model": "llama3-8b-8192",
|
|
|
128 |
{
|
129 |
"role": "system",
|
130 |
"content": (
|
131 |
+
"You are ToyBot, a friendly WhatsApp assistant for an online toy shop. "
|
132 |
+
"Help customers with toys, delivery, and returns in a helpful tone. "
|
133 |
+
"When responding, try to find the customer's name in the provided context "
|
134 |
+
"and address them directly. If the context contains order details and status, "
|
135 |
+
"include that information in your response."
|
136 |
)
|
137 |
},
|
138 |
{"role": "user", "content": prompt},
|
|
|
144 |
response.raise_for_status()
|
145 |
return response.json()['choices'][0]['message']['content'].strip()
|
146 |
|
147 |
+
# ---------------- Twilio Integration ----------------
|
148 |
def fetch_latest_incoming_message(client, conversation_sid):
|
149 |
try:
|
150 |
messages = client.conversations.v1.conversations(conversation_sid).messages.list()
|
|
|
157 |
"timestamp": msg.date_created,
|
158 |
}
|
159 |
except TwilioRestException as e:
|
160 |
+
print(f"Twilio error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
return None
|
162 |
|
163 |
def send_twilio_message(client, conversation_sid, body):
|
|
|
165 |
author="system", body=body
|
166 |
)
|
167 |
|
168 |
+
# ---------------- Knowledge Base Setup ----------------
|
169 |
def setup_knowledge_base():
|
170 |
folder_path = "docs"
|
171 |
all_text = ""
|
172 |
|
173 |
+
for filename in os.listdir(folder_path):
|
174 |
+
file_path = os.path.join(folder_path, filename)
|
175 |
+
if filename.endswith(".pdf"):
|
176 |
+
text, tables = extract_text_from_pdf(file_path)
|
177 |
+
all_text += clean_extracted_text(text) + "\n"
|
178 |
+
all_text += _format_tables_internal(tables) + "\n"
|
179 |
+
elif filename.endswith(".docx"):
|
180 |
+
text = extract_text_from_docx(file_path)
|
181 |
+
all_text += clean_extracted_text(text) + "\n"
|
182 |
+
elif filename.endswith(".json"):
|
183 |
+
text = load_json_data(file_path)
|
184 |
+
all_text += text + "\n"
|
185 |
+
elif filename.endswith(".csv"):
|
186 |
+
try:
|
187 |
+
with open(file_path, newline='', encoding='utf-8') as csvfile:
|
188 |
+
reader = csv.DictReader(csvfile)
|
189 |
+
for row in reader:
|
190 |
+
line = ' | '.join(f"{k}: {v}" for k, v in row.items())
|
191 |
+
all_text += line + "\n"
|
192 |
+
except Exception as e:
|
193 |
+
print(f"CSV read error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
|
|
|
195 |
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
|
196 |
chunks = chunk_text(all_text, tokenizer)
|
197 |
model = SentenceTransformer('all-mpnet-base-v2')
|
198 |
+
embeddings = model.encode(chunks, show_progress_bar=False)
|
199 |
dim = embeddings[0].shape[0]
|
200 |
index = faiss.IndexFlatL2(dim)
|
201 |
index.add(np.array(embeddings).astype('float32'))
|
202 |
return index, model, chunks
|
203 |
|
204 |
+
# ---------------- Monitor Twilio Conversations ----------------
|
|
|
|
|
205 |
def start_conversation_monitor(client, index, embed_model, text_chunks):
|
206 |
processed_convos = set()
|
207 |
last_processed_timestamp = {}
|
208 |
|
209 |
+
def poll_convo(convo_sid):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
while True:
|
211 |
+
latest_msg = fetch_latest_incoming_message(client, convo_sid)
|
212 |
+
if latest_msg:
|
213 |
+
msg_time = latest_msg["timestamp"]
|
214 |
+
if convo_sid not in last_processed_timestamp or msg_time > last_processed_timestamp[convo_sid]:
|
215 |
+
last_processed_timestamp[convo_sid] = msg_time
|
216 |
+
question = latest_msg["body"]
|
217 |
+
sender = latest_msg["author"]
|
218 |
+
print(f"π© New message from {sender}: {question}")
|
219 |
+
context = "\n\n".join(retrieve_chunks(question, index, embed_model, text_chunks))
|
220 |
+
answer = generate_answer_with_groq(question, context)
|
221 |
+
send_twilio_message(client, convo_sid, answer)
|
|
|
|
|
|
|
222 |
time.sleep(5)
|
223 |
|
224 |
+
for convo in client.conversations.v1.conversations.list():
|
225 |
+
if convo.sid not in processed_convos:
|
226 |
+
processed_convos.add(convo.sid)
|
227 |
+
threading.Thread(target=poll_convo, args=(convo.sid,), daemon=True).start()
|
228 |
|
229 |
+
# ---------------- Main Entry ----------------
|
230 |
+
if __name__ == "__main__":
|
231 |
+
st.title("π€ ToyBot WhatsApp Assistant")
|
232 |
+
st.write("Initializing knowledge base...")
|
233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
index, model, chunks = setup_knowledge_base()
|
235 |
+
|
236 |
+
st.success("Knowledge base loaded.")
|
237 |
+
st.write("Waiting for WhatsApp messages...")
|
238 |
+
|
239 |
+
account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
|
240 |
+
auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
|
241 |
+
if not account_sid or not auth_token:
|
242 |
+
st.error("β Twilio credentials not set.")
|
243 |
+
else:
|
244 |
+
client = Client(account_sid, auth_token)
|
245 |
+
start_conversation_monitor(client, index, model, chunks)
|
246 |
+
st.info("β
Bot is now monitoring Twilio conversations.")
|