masadonline commited on
Commit
4388ea1
Β·
verified Β·
1 Parent(s): 322de72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -74
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import time
3
  import threading
@@ -22,74 +23,79 @@ APP_START_TIME = datetime.datetime.now(datetime.timezone.utc)
22
 
23
  os.environ["PYTORCH_JIT"] = "0"
24
 
25
- # ---------------- PDF & DOCX & JSON Extraction ----------------
26
  def _extract_tables_from_page(page):
 
 
27
  tables = page.extract_tables()
 
 
 
28
  formatted_tables = []
29
  for table in tables:
30
  formatted_table = []
31
  for row in table:
32
- formatted_row = [cell if cell is not None else "" for cell in row]
33
- formatted_table.append(formatted_row)
 
 
 
34
  formatted_tables.append(formatted_table)
35
  return formatted_tables
36
-
37
  def extract_text_from_pdf(pdf_path):
38
  text_output = StringIO()
39
  all_tables = []
40
  try:
41
  with pdfplumber.open(pdf_path) as pdf:
42
  for page in pdf.pages:
43
- all_tables.extend(_extract_tables_from_page(page))
 
 
 
 
44
  text = page.extract_text()
45
  if text:
46
  text_output.write(text + "\n\n")
47
  except Exception as e:
48
- print(f"pdfplumber error: {e}")
 
49
  with open(pdf_path, 'rb') as file:
50
- extract_text_to_fp(file, text_output, laparams=LAParams(), output_type='text')
51
- return text_output.getvalue(), all_tables
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def _format_tables_internal(tables):
 
 
54
  formatted_tables_str = []
55
  for table in tables:
 
56
  with StringIO() as csvfile:
57
- writer = csv.writer(csvfile)
58
- writer.writerows(table)
59
  formatted_tables_str.append(csvfile.getvalue())
60
  return "\n\n".join(formatted_tables_str)
61
 
62
- def clean_extracted_text(text):
63
- return '\n'.join(' '.join(line.strip().split()) for line in text.splitlines() if line.strip())
64
-
65
  def extract_text_from_docx(docx_path):
66
  try:
67
  doc = docx.Document(docx_path)
68
  return '\n'.join(para.text for para in doc.paragraphs)
69
- except:
70
- return ""
71
-
72
- def load_json_data(json_path):
73
- try:
74
- with open(json_path, 'r', encoding='utf-8') as f:
75
- data = json.load(f)
76
- if isinstance(data, dict):
77
- # Flatten dictionary values (avoiding nested structures as strings)
78
- return "\n".join(f"{key}: {value}" for key, value in data.items() if not isinstance(value, (dict, list)))
79
- elif isinstance(data, list):
80
- # Flatten list of dictionaries
81
- all_items = []
82
- for item in data:
83
- if isinstance(item, dict):
84
- all_items.append("\n".join(f"{key}: {value}" for key, value in item.items() if not isinstance(value, (dict, list))))
85
- return "\n\n".join(all_items)
86
- else:
87
- return json.dumps(data, ensure_ascii=False, indent=2)
88
- except Exception as e:
89
- print(f"JSON read error: {e}")
90
  return ""
91
 
92
- # ---------------- Chunking ----------------
93
  def chunk_text(text, tokenizer, chunk_size=128, chunk_overlap=32, max_tokens=512):
94
  tokens = tokenizer.tokenize(text)
95
  chunks = []
@@ -104,13 +110,12 @@ def chunk_text(text, tokenizer, chunk_size=128, chunk_overlap=32, max_tokens=512
104
  start += chunk_size - chunk_overlap
105
  return chunks
106
 
107
-
108
  def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
109
- q_embedding = embed_model.encode(question)
110
- D, I = index.search(np.array([q_embedding]), k)
111
  return [text_chunks[i] for i in I[0]]
112
 
113
- # ---------------- Groq Answer Generator ----------------
114
  def generate_answer_with_groq(question, context):
115
  url = "https://api.groq.com/openai/v1/chat/completions"
116
  api_key = os.environ.get("GROQ_API_KEY")
@@ -120,9 +125,8 @@ def generate_answer_with_groq(question, context):
120
  }
121
  prompt = (
122
  f"Customer asked: '{question}'\n\n"
123
- f"Here is the relevant information to help:\n{context}\n\n"
124
- f"Respond in a friendly and helpful tone as a toy shop support agent, "
125
- f"addressing the customer by their name if it's available in the context."
126
  )
127
  payload = {
128
  "model": "llama3-8b-8192",
@@ -130,11 +134,9 @@ def generate_answer_with_groq(question, context):
130
  {
131
  "role": "system",
132
  "content": (
133
- "You are ToyBot, a friendly WhatsApp assistant for an online toy shop. "
134
- "Help customers with toys, delivery, and returns in a helpful tone. "
135
- "When responding, try to find the customer's name in the provided context "
136
- "and address them directly. If the context contains order details and status, "
137
- "include that information in your response."
138
  )
139
  },
140
  {"role": "user", "content": prompt},
@@ -174,37 +176,46 @@ def send_twilio_message(client, conversation_sid, body):
174
  author="system", body=body
175
  )
176
 
177
- # ---------------- Knowledge Base Setup ----------------
178
  def setup_knowledge_base():
179
  folder_path = "docs"
180
  all_text = ""
181
 
182
- for filename in os.listdir(folder_path):
183
- file_path = os.path.join(folder_path, filename)
184
- if filename.endswith(".pdf"):
185
- text, tables = extract_text_from_pdf(file_path)
186
- all_text += clean_extracted_text(text) + "\n"
187
- all_text += _format_tables_internal(tables) + "\n"
188
- elif filename.endswith(".docx"):
189
- text = extract_text_from_docx(file_path)
190
- all_text += clean_extracted_text(text) + "\n"
191
- elif filename.endswith(".json"):
192
- text = load_json_data(file_path)
193
- all_text += text + "\n"
194
- elif filename.endswith(".csv"):
195
- try:
196
- with open(file_path, newline='', encoding='utf-8') as csvfile:
197
- reader = csv.DictReader(csvfile)
198
- for row in reader:
199
- line = ' | '.join(f"{k}: {v}" for k, v in row.items())
200
- all_text += line + "\n"
201
- except Exception as e:
202
- print(f"CSV read error: {e}")
 
 
 
 
 
 
 
 
203
 
204
- tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased', model_max_length=512)
 
205
  chunks = chunk_text(all_text, tokenizer)
206
  model = SentenceTransformer('all-mpnet-base-v2')
207
- embeddings = model.encode(chunks, show_progress_bar=False)
208
  dim = embeddings[0].shape[0]
209
  index = faiss.IndexFlatL2(dim)
210
  index.add(np.array(embeddings).astype('float32'))
@@ -264,10 +275,7 @@ def start_conversation_monitor(client, index, embed_model, text_chunks):
264
  # --- Streamlit UI ---
265
  st.set_page_config(page_title="Quasa – Al-Powered WhatsApp Chatbot", layout="wide")
266
  st.title("πŸ“± Quasa – Al-Powered WhatsApp Chatbot")
267
- index, model, chunks = setup_knowledge_base()
268
 
269
- st.success("Knowledge base loaded.")
270
- #st.write("Waiting for WhatsApp messages...")
271
  account_sid = st.secrets.get("TWILIO_SID")
272
  auth_token = st.secrets.get("TWILIO_TOKEN")
273
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
 
1
+ #Backup
2
  import os
3
  import time
4
  import threading
 
23
 
24
  os.environ["PYTORCH_JIT"] = "0"
25
 
26
+ # --- PDF Extraction ---
27
  def _extract_tables_from_page(page):
28
+ """Extracts tables from a single page of a PDF."""
29
+
30
  tables = page.extract_tables()
31
+ if not tables:
32
+ return []
33
+
34
  formatted_tables = []
35
  for table in tables:
36
  formatted_table = []
37
  for row in table:
38
+ if row: # Filter out empty rows
39
+ formatted_row = [cell if cell is not None else "" for cell in row] # Replace None with ""
40
+ formatted_table.append(formatted_row)
41
+ else:
42
+ formatted_table.append([""]) # Append an empty row if the row is None
43
  formatted_tables.append(formatted_table)
44
  return formatted_tables
45
+
46
  def extract_text_from_pdf(pdf_path):
47
  text_output = StringIO()
48
  all_tables = []
49
  try:
50
  with pdfplumber.open(pdf_path) as pdf:
51
  for page in pdf.pages:
52
+ # Extract tables
53
+ page_tables = _extract_tables_from_page(page)
54
+ if page_tables:
55
+ all_tables.extend(page_tables)
56
+ # Extract text
57
  text = page.extract_text()
58
  if text:
59
  text_output.write(text + "\n\n")
60
  except Exception as e:
61
+ print(f"Error extracting with pdfplumber: {e}")
62
+ # Fallback to pdfminer if pdfplumber fails
63
  with open(pdf_path, 'rb') as file:
64
+ extract_text_to_fp(file, text_output, laparams=LAParams(), output_type='text', codec=None)
65
+ extracted_text = text_output.getvalue()
66
+ return extracted_text, all_tables # Return text and list of tables
67
+
68
+ def clean_extracted_text(text):
69
+ lines = text.splitlines()
70
+ cleaned = []
71
+ for line in lines:
72
+ line = line.strip()
73
+ if line:
74
+ line = ' '.join(line.split())
75
+ cleaned.append(line)
76
+ return '\n'.join(cleaned)
77
 
78
  def _format_tables_internal(tables):
79
+ """Formats extracted tables into a string representation."""
80
+
81
  formatted_tables_str = []
82
  for table in tables:
83
+ # Use csv writer to handle commas and quotes correctly
84
  with StringIO() as csvfile:
85
+ csvwriter = csv.writer(csvfile)
86
+ csvwriter.writerows(table)
87
  formatted_tables_str.append(csvfile.getvalue())
88
  return "\n\n".join(formatted_tables_str)
89
 
90
+ # --- DOCX Extraction ---
 
 
91
  def extract_text_from_docx(docx_path):
92
  try:
93
  doc = docx.Document(docx_path)
94
  return '\n'.join(para.text for para in doc.paragraphs)
95
+ except Exception:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  return ""
97
 
98
+ # --- Chunking ---
99
  def chunk_text(text, tokenizer, chunk_size=128, chunk_overlap=32, max_tokens=512):
100
  tokens = tokenizer.tokenize(text)
101
  chunks = []
 
110
  start += chunk_size - chunk_overlap
111
  return chunks
112
 
 
113
  def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
114
+ question_embedding = embed_model.encode(question)
115
+ D, I = index.search(np.array([question_embedding]), k)
116
  return [text_chunks[i] for i in I[0]]
117
 
118
+ # --- Groq Answer Generator ---
119
  def generate_answer_with_groq(question, context):
120
  url = "https://api.groq.com/openai/v1/chat/completions"
121
  api_key = os.environ.get("GROQ_API_KEY")
 
125
  }
126
  prompt = (
127
  f"Customer asked: '{question}'\n\n"
128
+ f"Here is the relevant product or policy info to help:\n{context}\n\n"
129
+ f"Respond in a friendly and helpful tone as a toy shop support agent."
 
130
  )
131
  payload = {
132
  "model": "llama3-8b-8192",
 
134
  {
135
  "role": "system",
136
  "content": (
137
+ "You are ToyBot, a friendly and helpful WhatsApp assistant for an online toy shop. "
138
+ "Your goal is to politely answer customer questions, help them choose the right toys, "
139
+ "provide order or delivery information, explain return policies, and guide them through purchases."
 
 
140
  )
141
  },
142
  {"role": "user", "content": prompt},
 
176
  author="system", body=body
177
  )
178
 
179
+ # --- Load Knowledge Base ---
180
  def setup_knowledge_base():
181
  folder_path = "docs"
182
  all_text = ""
183
 
184
+ # Process PDFs
185
+ for filename in ["FAQ.pdf", "ProductReturnPolicy.pdf"]:
186
+ pdf_path = os.path.join(folder_path, filename)
187
+ text, tables = extract_text_from_pdf(pdf_path)
188
+ all_text += clean_extracted_text(text) + "\n"
189
+ all_text += _format_tables_internal(tables) + "\n"
190
+
191
+ # Process CSVs
192
+ for filename in ["CustomerOrders.csv"]:
193
+ csv_path = os.path.join(folder_path, filename)
194
+ try:
195
+ with open(csv_path, newline='', encoding='utf-8') as csvfile:
196
+ reader = csv.DictReader(csvfile)
197
+ for row in reader:
198
+ line = f"Order ID: {row.get('OrderID')} | Customer Name: {row.get('CustomerName')} | Order Date: {row.get('OrderDate')} | ProductID: {row.get('ProductID')} | Date: {row.get('OrderDate')} | Quantity: {row.get('Quantity')} | UnitPrice(USD): {row.get('UnitPrice(USD)')} | TotalPrice(USD): {row.get('TotalPrice(USD)')} | ShippingAddress: {row.get('ShippingAddress')} | OrderStatus: {row.get('OrderStatus')}"
199
+ all_text += line + "\n"
200
+ except Exception as e:
201
+ print(f"❌ Error reading {filename}: {e}")
202
+
203
+ for filename in ["Products.csv"]:
204
+ csv_path = os.path.join(folder_path, filename)
205
+ try:
206
+ with open(csv_path, newline='', encoding='utf-8') as csvfile:
207
+ reader = csv.DictReader(csvfile)
208
+ for row in reader:
209
+ 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')}"
210
+ all_text += line + "\n"
211
+ except Exception as e:
212
+ print(f"❌ Error reading {filename}: {e}")
213
 
214
+ # Tokenization & chunking
215
+ tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
216
  chunks = chunk_text(all_text, tokenizer)
217
  model = SentenceTransformer('all-mpnet-base-v2')
218
+ embeddings = model.encode(chunks, show_progress_bar=False, truncation=True, max_length=512)
219
  dim = embeddings[0].shape[0]
220
  index = faiss.IndexFlatL2(dim)
221
  index.add(np.array(embeddings).astype('float32'))
 
275
  # --- Streamlit UI ---
276
  st.set_page_config(page_title="Quasa – Al-Powered WhatsApp Chatbot", layout="wide")
277
  st.title("πŸ“± Quasa – Al-Powered WhatsApp Chatbot")
 
278
 
 
 
279
  account_sid = st.secrets.get("TWILIO_SID")
280
  auth_token = st.secrets.get("TWILIO_TOKEN")
281
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")