masadonline commited on
Commit
7a5db40
·
verified ·
1 Parent(s): e1b5dcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -86
app.py CHANGED
@@ -22,99 +22,92 @@ APP_START_TIME = datetime.datetime.now(datetime.timezone.utc)
22
 
23
  os.environ["PYTORCH_JIT"] = "0"
24
 
25
- # --- PDF Extraction ---
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 row: # Filter out empty rows
38
- formatted_row = [cell if cell is not None else "" for cell in row] # Replace None with ""
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
- # Extract tables
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"Error extracting with pdfplumber: {e}")
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', codec=None)
64
- extracted_text = text_output.getvalue()
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
- csvwriter = csv.writer(csvfile)
85
- csvwriter.writerows(table)
86
  formatted_tables_str.append(csvfile.getvalue())
87
  return "\n\n".join(formatted_tables_str)
88
 
89
- # --- DOCX Extraction ---
 
 
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 Exception:
95
  return ""
96
 
97
- # --- Chunking ---
98
- def chunk_text(text, tokenizer, chunk_size=128, chunk_overlap=32, max_tokens=512):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  tokens = tokenizer.tokenize(text)
100
  chunks = []
101
  start = 0
102
  while start < len(tokens):
103
  end = min(start + chunk_size, len(tokens))
104
- chunk_tokens = tokens[start:end]
105
- chunk_text = tokenizer.convert_tokens_to_string(chunk_tokens)
106
- chunks.append(chunk_text)
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
- question_embedding = embed_model.encode(question)
114
- D, I = index.search(np.array([question_embedding]), k)
115
  return [text_chunks[i] for i in I[0]]
116
 
117
- # --- Groq Answer Generator ---
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 +117,9 @@ def generate_answer_with_groq(question, context):
124
  }
125
  prompt = (
126
  f"Customer asked: '{question}'\n\n"
127
- f"Here is the relevant product or policy info to help:\n{context}\n\n"
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 +127,11 @@ def generate_answer_with_groq(question, context):
133
  {
134
  "role": "system",
135
  "content": (
136
- "You are ToyBot, a friendly and helpful WhatsApp assistant for an online toy shop. "
137
- "Your goal is to politely answer customer questions, help them choose the right toys, "
138
- "provide order or delivery information, explain return policies, and guide them through purchases."
 
 
139
  )
140
  },
141
  {"role": "user", "content": prompt},
@@ -175,46 +171,37 @@ def send_twilio_message(client, conversation_sid, body):
175
  author="system", body=body
176
  )
177
 
178
- # --- Load Knowledge Base ---
179
  def setup_knowledge_base():
180
  folder_path = "docs"
181
  all_text = ""
182
 
183
- # Process PDFs
184
- for filename in ["FAQ.pdf", "ProductReturnPolicy.pdf"]:
185
- pdf_path = os.path.join(folder_path, filename)
186
- text, tables = extract_text_from_pdf(pdf_path)
187
- all_text += clean_extracted_text(text) + "\n"
188
- all_text += _format_tables_internal(tables) + "\n"
189
-
190
- # Process CSVs
191
- for filename in ["CustomerOrders.csv"]:
192
- csv_path = os.path.join(folder_path, filename)
193
- try:
194
- with open(csv_path, newline='', encoding='utf-8') as csvfile:
195
- reader = csv.DictReader(csvfile)
196
- for row in reader:
197
- 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')}"
198
- all_text += line + "\n"
199
- except Exception as e:
200
- print(f"❌ Error reading {filename}: {e}")
201
-
202
- for filename in ["Products.csv"]:
203
- csv_path = os.path.join(folder_path, filename)
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, truncation=True, max_length=512)
218
  dim = embeddings[0].shape[0]
219
  index = faiss.IndexFlatL2(dim)
220
  index.add(np.array(embeddings).astype('float32'))
@@ -274,7 +261,10 @@ def start_conversation_monitor(client, index, embed_model, text_chunks):
274
  # --- Streamlit UI ---
275
  st.set_page_config(page_title="Quasa – Al-Powered WhatsApp Chatbot", layout="wide")
276
  st.title("📱 Quasa – Al-Powered WhatsApp Chatbot")
 
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")
 
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):
94
  tokens = tokenizer.tokenize(text)
95
  chunks = []
96
  start = 0
97
  while start < len(tokens):
98
  end = min(start + chunk_size, len(tokens))
99
+ chunk = tokens[start:end]
100
+ chunks.append(tokenizer.convert_tokens_to_string(chunk))
101
+ if end == len(tokens): break
 
 
102
  start += chunk_size - chunk_overlap
103
  return chunks
104
 
105
  def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
106
+ q_embedding = embed_model.encode(question)
107
+ D, I = index.search(np.array([q_embedding]), k)
108
  return [text_chunks[i] for i in I[0]]
109
 
110
+ # ---------------- Groq Answer Generator ----------------
111
  def generate_answer_with_groq(question, context):
112
  url = "https://api.groq.com/openai/v1/chat/completions"
113
  api_key = os.environ.get("GROQ_API_KEY")
 
117
  }
118
  prompt = (
119
  f"Customer asked: '{question}'\n\n"
120
+ f"Here is the relevant information to help:\n{context}\n\n"
121
+ f"Respond in a friendly and helpful tone as a toy shop support agent, "
122
+ f"addressing the customer by their name if it's available in the context."
123
  )
124
  payload = {
125
  "model": "llama3-8b-8192",
 
127
  {
128
  "role": "system",
129
  "content": (
130
+ "You are ToyBot, a friendly WhatsApp assistant for an online toy shop. "
131
+ "Help customers with toys, delivery, and returns in a helpful tone. "
132
+ "When responding, try to find the customer's name in the provided context "
133
+ "and address them directly. If the context contains order details and status, "
134
+ "include that information in your response."
135
  )
136
  },
137
  {"role": "user", "content": prompt},
 
171
  author="system", body=body
172
  )
173
 
174
+ # ---------------- Knowledge Base Setup ----------------
175
  def setup_knowledge_base():
176
  folder_path = "docs"
177
  all_text = ""
178
 
179
+ for filename in os.listdir(folder_path):
180
+ file_path = os.path.join(folder_path, filename)
181
+ if filename.endswith(".pdf"):
182
+ text, tables = extract_text_from_pdf(file_path)
183
+ all_text += clean_extracted_text(text) + "\n"
184
+ all_text += _format_tables_internal(tables) + "\n"
185
+ elif filename.endswith(".docx"):
186
+ text = extract_text_from_docx(file_path)
187
+ all_text += clean_extracted_text(text) + "\n"
188
+ elif filename.endswith(".json"):
189
+ text = load_json_data(file_path)
190
+ all_text += text + "\n"
191
+ elif filename.endswith(".csv"):
192
+ try:
193
+ with open(file_path, newline='', encoding='utf-8') as csvfile:
194
+ reader = csv.DictReader(csvfile)
195
+ for row in reader:
196
+ line = ' | '.join(f"{k}: {v}" for k, v in row.items())
197
+ all_text += line + "\n"
198
+ except Exception as e:
199
+ print(f"CSV read error: {e}")
 
 
 
 
 
 
 
 
200
 
 
201
  tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
202
  chunks = chunk_text(all_text, tokenizer)
203
  model = SentenceTransformer('all-mpnet-base-v2')
204
+ embeddings = model.encode(chunks, show_progress_bar=False)
205
  dim = embeddings[0].shape[0]
206
  index = faiss.IndexFlatL2(dim)
207
  index.add(np.array(embeddings).astype('float32'))
 
261
  # --- Streamlit UI ---
262
  st.set_page_config(page_title="Quasa – Al-Powered WhatsApp Chatbot", layout="wide")
263
  st.title("📱 Quasa – Al-Powered WhatsApp Chatbot")
264
+ index, model, chunks = setup_knowledge_base()
265
 
266
+ st.success("Knowledge base loaded.")
267
+ #st.write("Waiting for WhatsApp messages...")
268
  account_sid = st.secrets.get("TWILIO_SID")
269
  auth_token = st.secrets.get("TWILIO_TOKEN")
270
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")