LeedsLibraries commited on
Commit
dd0b292
·
verified ·
1 Parent(s): ace2847

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +1305 -0
  2. requirements (2).txt +13 -0
  3. runtime (1).txt +1 -0
app.py ADDED
@@ -0,0 +1,1305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import numpy as np
3
+ import os
4
+ import re
5
+ import streamlit as st
6
+ import streamlit.components.v1 as components
7
+ import torch
8
+ import glob
9
+ from datetime import datetime
10
+ from langchain_community.vectorstores import FAISS # Add this line
11
+
12
+ #from huggingface_hub import HfFolder
13
+ from langchain_community.document_loaders import PyPDFLoader
14
+ from langchain_text_splitters import CharacterTextSplitter
15
+
16
+ #from langchain.text_splitter import CharacterTextSplitter
17
+ from langchain_community.vectorstores import Chroma
18
+ from langchain_huggingface import HuggingFaceEmbeddings
19
+ #from sentence_transformers import util
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
21
+
22
+ # ====== CONFIGURATION SECTION ======
23
+ APP_TITLE = "Educational PDF Chatbot"
24
+ APP_LAYOUT = "wide"
25
+ MODEL_NAME = "Qwen/Qwen2.5-14B-Instruct"
26
+
27
+ EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
28
+
29
+ CHUNK_SIZE = 1200 # Reduced from 2000
30
+ CHUNK_OVERLAP = 100 # Reduced from 300
31
+ SEARCH_K = 4 # Reduced from 7
32
+ MIN_SIMILARITY_THRESHOLD = 0.1
33
+ MAX_CONVERSATION_HISTORY = 6
34
+
35
+ PDF_SEARCH_PATHS = [
36
+ "*.pdf",
37
+ "Data/*.pdf",
38
+ "documents/*.pdf",
39
+ "pdfs/*.pdf"
40
+ ]
41
+
42
+ # Response style configurations
43
+ RESPONSE_STYLES = {
44
+ 'Balanced': {'temperature': 0.1, 'max_tokens': 500},
45
+ 'Concise': {'temperature': 0.05, 'max_tokens': 300},
46
+ 'Detailed': {'temperature': 0.2, 'max_tokens': 700}
47
+ }
48
+
49
+ SAFETY_CONFIG = {
50
+ 'enable_strict_mode': False,
51
+ 'educational_alternatives': True,
52
+ 'allow_general_knowledge': True
53
+ }
54
+
55
+ CHATBOT_PASSWORD = st.secrets.get("CHATBOT_PASSWORD", os.getenv("CHATBOT_PASSWORD", "edu123"))
56
+
57
+ # ====== END CONFIGURATION SECTION ======
58
+
59
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
60
+ os.environ["HF_HUB_DISABLE_EXPERIMENTAL_WARNING"] = "1"
61
+ os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "0"
62
+
63
+ np.float_ = np.float64
64
+ st.set_page_config(page_title=APP_TITLE, layout=APP_LAYOUT)
65
+
66
+ # ====== COPY BUTTON FUNCTION ======
67
+ def create_copy_button(text, button_id):
68
+ """Create a working copy button using Streamlit components."""
69
+ button_html = f"""
70
+ <div style="margin-top: 0.5rem;">
71
+ <button
72
+ id="{button_id}"
73
+ onclick="copyText_{button_id}()"
74
+ style="
75
+ background-color: #5E35B1;
76
+ color: white;
77
+ border: none;
78
+ padding: 0.4rem 0.8rem;
79
+ border-radius: 0.3rem;
80
+ cursor: pointer;
81
+ font-size: 0.85rem;
82
+ transition: all 0.2s ease;
83
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
84
+ "
85
+ onmouseover="this.style.backgroundColor='#7E57C2'; this.style.transform='translateY(-2px)'"
86
+ onmouseout="this.style.backgroundColor='#5E35B1'; this.style.transform='translateY(0)'"
87
+ >
88
+ 📋 Copy Response
89
+ </button>
90
+ <span id="feedback_{button_id}" style="color: #4CAF50; font-size: 0.85rem; margin-left: 0.5rem; font-weight: 500;"></span>
91
+ </div>
92
+ <script>
93
+ function copyText_{button_id}() {{
94
+ const text = {repr(text)};
95
+ navigator.clipboard.writeText(text).then(function() {{
96
+ const button = document.getElementById("{button_id}");
97
+ const feedback = document.getElementById("feedback_{button_id}");
98
+ const originalText = button.innerHTML;
99
+ button.innerHTML = '✓ Copied!';
100
+ button.style.backgroundColor = '#4CAF50';
101
+ feedback.innerHTML = '';
102
+ setTimeout(function() {{
103
+ button.innerHTML = originalText;
104
+ button.style.backgroundColor = '#5E35B1';
105
+ }}, 2000);
106
+ }}).catch(function(err) {{
107
+ const feedback = document.getElementById("feedback_{button_id}");
108
+ feedback.innerHTML = '❌ Copy failed';
109
+ feedback.style.color = '#f44336';
110
+ console.error('Copy failed:', err);
111
+ setTimeout(function() {{
112
+ feedback.innerHTML = '';
113
+ }}, 3000);
114
+ }});
115
+ }}
116
+ </script>
117
+ """
118
+ components.html(button_html, height=60)
119
+
120
+ # ====== AUTHENTICATION SYSTEM ======
121
+ def check_password():
122
+ """Check password and manage authentication."""
123
+ if "authenticated" not in st.session_state:
124
+ st.session_state.authenticated = False
125
+ if "login_attempts" not in st.session_state:
126
+ st.session_state.login_attempts = 0
127
+
128
+ if st.session_state.authenticated:
129
+ return True
130
+
131
+ st.markdown("""
132
+ <div style='text-align: center; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 2rem;'>
133
+ <h1 style='color: white; margin-bottom: 1rem;'>🔒 Educational PDF Chatbot</h1>
134
+ <p style='color: white; font-size: 1.1em;'>Authentication required</p>
135
+ </div>
136
+ """, unsafe_allow_html=True)
137
+
138
+ if st.session_state.login_attempts >= 5:
139
+ st.error("Too many failed attempts. Please wait a few minutes.")
140
+ st.stop()
141
+
142
+ with st.form("login_form"):
143
+ st.subheader("Enter Password")
144
+ password = st.text_input("Password", type="password", placeholder="Access password")
145
+ submit_button = st.form_submit_button("Access", use_container_width=True)
146
+
147
+ if submit_button:
148
+ if password == CHATBOT_PASSWORD:
149
+ st.session_state.authenticated = True
150
+ st.session_state.login_attempts = 0
151
+ st.rerun()
152
+ else:
153
+ st.session_state.login_attempts += 1
154
+ remaining = 5 - st.session_state.login_attempts
155
+ if remaining > 0:
156
+ st.error(f"Incorrect password. Attempts remaining: {remaining}")
157
+ else:
158
+ st.error("Access temporarily blocked.")
159
+ return False
160
+
161
+ if not check_password():
162
+ st.stop()
163
+
164
+ # ====== SESSION STATE INITIALIZATION ======
165
+ if "messages" not in st.session_state:
166
+ st.session_state.messages = []
167
+ if "conversation_id" not in st.session_state:
168
+ st.session_state.conversation_id = 0
169
+ if "model_loaded" not in st.session_state:
170
+ st.session_state.model_loaded = False
171
+ if "response_style" not in st.session_state:
172
+ st.session_state.response_style = "Balanced"
173
+ if "retriever" not in st.session_state: # ← ADDED
174
+ st.session_state.retriever = None # ← ADDED
175
+ if "model" not in st.session_state: # ← ADD
176
+ st.session_state.model = None # ← ADD
177
+ if "tokenizer" not in st.session_state: # ← ADD
178
+ st.session_state.tokenizer = None # ← ADD
179
+
180
+ # ====== API CONFIGURATION ======
181
+ HF_API_KEY = st.secrets.get("HF_TOKEN", os.getenv("HF_TOKEN"))
182
+
183
+ #if HF_API_KEY:
184
+ #HfFolder.save_token(HF_API_KEY)
185
+
186
+ if not HF_API_KEY:
187
+ st.error("Hugging Face API key is missing.")
188
+ st.stop()
189
+
190
+ @st.cache_resource
191
+ def load_quantized_model():
192
+ """Load model with 4-bit quantization."""
193
+ try:
194
+ quantization_config = BitsAndBytesConfig(
195
+ load_in_4bit=True,
196
+ bnb_4bit_compute_dtype=torch.float16,
197
+ bnb_4bit_use_double_quant=True,
198
+ bnb_4bit_quant_type="nf4"
199
+ )
200
+
201
+ tokenizer = AutoTokenizer.from_pretrained(
202
+ MODEL_NAME,
203
+ token=HF_API_KEY,
204
+ trust_remote_code=True,
205
+ use_fast=True,
206
+ padding_side="left",
207
+ )
208
+
209
+ if tokenizer.pad_token is None:
210
+ tokenizer.pad_token = tokenizer.eos_token
211
+ tokenizer.pad_token_id = tokenizer.eos_token_id
212
+
213
+ model = AutoModelForCausalLM.from_pretrained(
214
+ MODEL_NAME,
215
+ device_map="auto",
216
+ torch_dtype=torch.float16,
217
+ quantization_config=quantization_config,
218
+ token=HF_API_KEY,
219
+ low_cpu_mem_usage=True,
220
+ trust_remote_code=True,
221
+ )
222
+
223
+ return model, tokenizer
224
+ except Exception as e:
225
+ st.error(f"Error loading model: {str(e)}")
226
+ return None, None
227
+
228
+
229
+
230
+ def check_question_safety(question):
231
+ """Enhanced safety check with improved precision."""
232
+ question_lower = question.lower().strip()
233
+
234
+ profanity_patterns = [
235
+ r'\bfuck\b', r'\bfucking\b', r'\bfucked\b', r'\bfucker\b',
236
+ r'\bshit\b', r'\bshitty\b', r'\bshitting\b',
237
+ r'\bbitch\b', r'\bbitching\b', r'\bbitchy\b',
238
+ r'\bass\b(?!\w)', r'\basshole\b',
239
+ r'\bdamn\b(?!\w)',
240
+ r'\bcrap\b', r'\bcrappy\b'
241
+ ]
242
+
243
+ for pattern in profanity_patterns:
244
+ if re.search(pattern, question_lower):
245
+ return False, "I'd prefer to keep our conversation respectful and educational."
246
+
247
+ unsafe_patterns = [
248
+ r'\b(kill|murder|hurt|harm|attack|violence|weapon|bomb|suicide)\b',
249
+ r'\bself[\s\-]harm\b',
250
+ r'\b(illegal\s+drugs|hack\s+into|steal\s+from|fraud|piracy|money\s+laundering)\b',
251
+ r'\bhow\s+to\s+(hack|steal|forge|counterfeit)\b',
252
+ r'\b(personal\s+address|phone\s+number|social\s+security|password|credit\s+card)\b',
253
+ r'\bprivate\s+information\b',
254
+ r'\b(hate\s+speech|racist\s+jokes|discrimination\s+against|offensive\s+slur)\b',
255
+ r'\bextremist\s+(content|views|ideology)\b',
256
+ r'\b(sexual\s+content|pornographic|explicit\s+content|adult\s+material)\b',
257
+ r'\b(sexy|erotic|intimate|adult\s+humor)\b',
258
+ r'\b(sexual\s+joke|dirty\s+joke|adult\s+joke)\b'
259
+ ]
260
+
261
+ for pattern in unsafe_patterns:
262
+ if re.search(pattern, question_lower):
263
+ return False, "I keep conversations appropriate and educational."
264
+
265
+ educational_inappropriate = [
266
+ 'how to cheat on', 'academic dishonesty', 'plagiarism methods', 'fake certificates',
267
+ 'exam answers for', 'homework answers for', 'cheat codes for', 'bypass security'
268
+ ]
269
+
270
+ for phrase in educational_inappropriate:
271
+ if phrase in question_lower:
272
+ return False, "I'm designed to support ethical learning."
273
+
274
+ return True, ""
275
+
276
+ def generate_educational_alternative(declined_topic):
277
+ """Provide educational alternatives."""
278
+ if not SAFETY_CONFIG['educational_alternatives']:
279
+ return ""
280
+
281
+ alternatives = {
282
+ 'violence': "I can help with conflict resolution, peace studies, or historical context.",
283
+ 'illegal': "I can provide information about legal systems, ethics, or policy studies.",
284
+ 'harm': "I can help with safety education, health information, or wellness topics.",
285
+ 'academic_dishonesty': "I can help you understand the topic better or provide study strategies."
286
+ }
287
+
288
+ for key, alternative in alternatives.items():
289
+ if key in declined_topic.lower():
290
+ return f"\n\n{alternative}"
291
+
292
+ return "\n\nI'm here to help with educational topics and research questions."
293
+
294
+ def clean_document_text(text):
295
+ """Clean document text."""
296
+ if not text:
297
+ return text
298
+ import unicodedata
299
+ try:
300
+ text = unicodedata.normalize('NFKD', text)
301
+ except:
302
+ pass
303
+ text = re.sub(r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]', '', text)
304
+ text = re.sub(r'[^\x00-\x7F\u00C0-\u00FF]', '', text)
305
+ text = re.sub(r'\s+', ' ', text)
306
+ return text.strip()
307
+
308
+ def get_pdf_files():
309
+ """Discover all PDF files."""
310
+ pdf_files = []
311
+ for search_path in PDF_SEARCH_PATHS:
312
+ found_files = glob.glob(search_path)
313
+ pdf_files.extend(found_files)
314
+ pdf_files = list(set(pdf_files))
315
+ pdf_files.sort()
316
+ return pdf_files
317
+
318
+ PDF_FILES = get_pdf_files()
319
+
320
+ if not PDF_FILES:
321
+ st.error("No PDF files found.")
322
+ st.stop()
323
+
324
+
325
+ @st.cache_resource
326
+ def get_embeddings():
327
+ """Load embeddings on CPU to avoid GPU contention."""
328
+ return HuggingFaceEmbeddings(
329
+ model_name=EMBEDDING_MODEL,
330
+ model_kwargs={"token": HF_API_KEY} # CPU only - no device="cuda"
331
+ )
332
+
333
+ @st.cache_resource
334
+ def load_and_index_pdfs():
335
+ """Fast in-memory FAISS index - no disk persistence issues."""
336
+ from langchain_community.vectorstores import FAISS
337
+
338
+ status = st.empty()
339
+ progress = st.progress(0)
340
+
341
+ try:
342
+ # 1) Load embeddings first
343
+ status.write("🔢 Loading embedding model...")
344
+ embeddings = get_embeddings()
345
+ status.write("✅ Embedding model ready")
346
+ progress.progress(10)
347
+
348
+ # 2) Load PDFs
349
+ status.write("📄 Loading PDFs...")
350
+ documents = []
351
+ total_pdfs = len(PDF_FILES)
352
+
353
+ for idx, pdf in enumerate(PDF_FILES, start=1):
354
+ status.write(f"📄 Processing {os.path.basename(pdf)} ({idx}/{total_pdfs})...")
355
+ try:
356
+ loader = PyPDFLoader(pdf)
357
+ docs = loader.load()
358
+
359
+ for doc in docs:
360
+ doc.metadata["source"] = f"{os.path.basename(pdf)} (Page {doc.metadata.get('page', 0)+1})"
361
+ doc.page_content = clean_document_text(doc.page_content)
362
+
363
+ documents.extend(docs)
364
+ status.write(f" ✅ {len(docs)} pages loaded")
365
+ except Exception as e:
366
+ status.write(f"⚠️ Skipping {os.path.basename(pdf)}: {str(e)}")
367
+
368
+ progress.progress(10 + int(30 * idx / total_pdfs))
369
+
370
+ if not documents:
371
+ status.write("❌ No documents loaded")
372
+ progress.empty()
373
+ status.empty()
374
+ return None
375
+
376
+ status.write(f"✅ Loaded {len(documents)} pages total")
377
+ progress.progress(40)
378
+
379
+ # 3) Split documents
380
+ status.write("✂️ Splitting into chunks...")
381
+ text_splitter = CharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
382
+ splits = text_splitter.split_documents(documents)
383
+ status.write(f"✅ Created {len(splits)} chunks")
384
+ progress.progress(50)
385
+
386
+ # 4) Embed in batches with FAISS
387
+ status.write(f"🔢 Creating vector index for {len(splits)} chunks...")
388
+
389
+ BATCH_SIZE = 25 # Small batches for progress visibility
390
+ total_batches = (len(splits) - 1) // BATCH_SIZE + 1
391
+ vectorstore = None
392
+ successful_batches = 0
393
+
394
+ for i in range(0, len(splits), BATCH_SIZE):
395
+ batch = splits[i:i+BATCH_SIZE]
396
+ batch_num = i // BATCH_SIZE + 1
397
+
398
+ status.write(f"🔢 Batch {batch_num}/{total_batches} ({len(batch)} chunks)...")
399
+
400
+ try:
401
+ if vectorstore is None:
402
+ # Create FAISS index with first batch
403
+ vectorstore = FAISS.from_documents(batch, embeddings)
404
+ else:
405
+ # Add subsequent batches
406
+ vectorstore.add_documents(batch)
407
+
408
+ successful_batches += 1
409
+
410
+ # Update progress (50% to 100%)
411
+ done = min(i + len(batch), len(splits))
412
+ batch_progress = 50 + int(50 * done / len(splits))
413
+ progress.progress(batch_progress)
414
+
415
+ except Exception as e:
416
+ status.write(f"⚠️ Error in batch {batch_num}: {str(e)}")
417
+ # Don't continue - we need to know if embedding is broken
418
+ if successful_batches == 0:
419
+ raise Exception(f"Failed to embed first batch: {str(e)}")
420
+
421
+ if successful_batches == 0:
422
+ status.write("❌ No batches were successfully embedded")
423
+ progress.empty()
424
+ status.empty()
425
+ return None
426
+
427
+ progress.progress(100)
428
+ status.write(f"✅ Knowledge base ready! ({successful_batches}/{total_batches} batches)")
429
+
430
+ # Clear UI after brief pause (but don't block)
431
+ progress.empty()
432
+ status.empty()
433
+
434
+ return vectorstore.as_retriever(search_kwargs={"k": SEARCH_K})
435
+
436
+ except Exception as e:
437
+ status.write(f"❌ Failed: {str(e)}")
438
+ st.error(f"Error building knowledge base: {str(e)}")
439
+ progress.empty()
440
+ status.empty()
441
+ return None
442
+
443
+ # ← ADDED: Lazy loading helper function
444
+ def get_retriever():
445
+ """Lazy load retriever only when needed."""
446
+ if st.session_state.retriever is None:
447
+ with st.spinner("📚 Loading knowledge base... (first time only)"):
448
+ st.session_state.retriever = load_and_index_pdfs()
449
+ return st.session_state.retriever
450
+
451
+ def get_model():
452
+ """Lazy load model only when generating response."""
453
+ if st.session_state.model is None:
454
+ with st.spinner("🤖 Loading AI model..."):
455
+ st.session_state.model, st.session_state.tokenizer = load_quantized_model()
456
+ return st.session_state.model, st.session_state.tokenizer
457
+
458
+ def clean_message_content(content):
459
+ """Clean message content."""
460
+ if not content:
461
+ return ""
462
+ content = re.sub(r'Source:.*?(?=\n|$)', '', content, flags=re.DOTALL)
463
+ content = re.sub(r'Follow-up.*?(?=\n|$)', '', content, flags=re.DOTALL)
464
+ content = re.sub(r'\n{3,}', '\n\n', content)
465
+ return content.strip()
466
+
467
+ def needs_pronoun_resolution(query):
468
+ """Check if query contains pronouns."""
469
+ query_lower = query.lower()
470
+ pronouns_to_check = ['they', 'them', 'their', 'it', 'its', 'this', 'that', 'these', 'those']
471
+ return any(f' {pronoun} ' in f' {query_lower} ' or
472
+ query_lower.startswith(f'{pronoun} ') or
473
+ query_lower.endswith(f' {pronoun}')
474
+ for pronoun in pronouns_to_check)
475
+
476
+ def detect_pronouns_and_resolve(query, conversation_history):
477
+ """Detect and resolve pronouns using context."""
478
+ query_lower = query.lower()
479
+ pronouns = {
480
+ 'they': [], 'them': [], 'their': [], 'theirs': [],
481
+ 'it': [], 'its': [], 'this': [], 'that': [], 'these': [], 'those': [],
482
+ 'he': [], 'him': [], 'his': [], 'she': [], 'her': [], 'hers': []
483
+ }
484
+
485
+ found_pronouns = []
486
+ for pronoun in pronouns.keys():
487
+ if f' {pronoun} ' in f' {query_lower} ' or query_lower.startswith(f'{pronoun} ') or query_lower.endswith(f' {pronoun}'):
488
+ found_pronouns.append(pronoun)
489
+
490
+ if not found_pronouns:
491
+ return query, False
492
+
493
+ if len(conversation_history) < 2:
494
+ return query, False
495
+
496
+ last_user_msg = ""
497
+ last_assistant_msg = ""
498
+
499
+ for msg in reversed(conversation_history):
500
+ if msg["role"] == "user" and not last_user_msg:
501
+ last_user_msg = msg["content"]
502
+ elif msg["role"] == "assistant" and not last_assistant_msg:
503
+ last_assistant_msg = clean_message_content(msg["content"])
504
+ if last_user_msg and last_assistant_msg:
505
+ break
506
+
507
+ potential_referents = []
508
+ entity_patterns = [
509
+ r'\b([A-Z][a-z]+ [A-Z][a-z]+)\b',
510
+ r'\b([a-z]+ [a-z]+(?:ies|tion|ment|ness|ity))\b',
511
+ r'\b(organizations?|institutions?|companies?|governments?|agencies?|groups?)\b',
512
+ r'\b(students?|teachers?|researchers?|scientists?|experts?|professionals?)\b',
513
+ r'\b(countries?|nations?|regions?|communities?|populations?)\b'
514
+ ]
515
+
516
+ combined_text = f"{last_user_msg} {last_assistant_msg}"
517
+ for pattern in entity_patterns:
518
+ matches = re.findall(pattern, combined_text, re.IGNORECASE)
519
+ potential_referents.extend(matches)
520
+
521
+ best_referent = None
522
+ for ref in potential_referents:
523
+ if len(ref.split()) > 1:
524
+ best_referent = ref
525
+ break
526
+
527
+ if not best_referent and potential_referents:
528
+ best_referent = potential_referents[0]
529
+
530
+ if best_referent:
531
+ expanded_query = query
532
+ for pronoun in found_pronouns:
533
+ if pronoun in ['they', 'them', 'their', 'theirs']:
534
+ if pronoun == 'they':
535
+ expanded_query = re.sub(rf'\bthey\b', best_referent, expanded_query, flags=re.IGNORECASE)
536
+ elif pronoun == 'them':
537
+ expanded_query = re.sub(rf'\bthem\b', best_referent, expanded_query, flags=re.IGNORECASE)
538
+ elif pronoun == 'their':
539
+ expanded_query = re.sub(rf'\btheir\b', f"{best_referent}'s", expanded_query, flags=re.IGNORECASE)
540
+ return expanded_query, True
541
+
542
+ return query, False
543
+
544
+ def get_document_topics():
545
+ """Extract clean topics from documents."""
546
+ if not PDF_FILES:
547
+ return []
548
+ topics = []
549
+ for pdf in PDF_FILES:
550
+ filename = os.path.basename(pdf).lower()
551
+ clean_name = filename
552
+ if clean_name.endswith('.pdf'):
553
+ clean_name = clean_name[:-4]
554
+ clean_name = re.sub(r'[_-]+', ' ', clean_name)
555
+ clean_name = re.sub(r'^\d+\s*', '', clean_name)
556
+ stop_words = ['document', 'file', 'report', 'briefing', 'overview', 'web', 'pdf']
557
+ words = [word for word in clean_name.split() if word not in stop_words and len(word) > 2]
558
+ if words:
559
+ clean_topic = ' '.join(words[:4])
560
+ clean_topic = ' '.join(word.capitalize() for word in clean_topic.split())
561
+ topics.append(clean_topic)
562
+ unique_topics = list(dict.fromkeys(topics))[:5]
563
+ return unique_topics
564
+
565
+ def handle_topic_questions(prompt):
566
+ """Handle questions about available topics."""
567
+ prompt_lower = prompt.lower()
568
+ topic_question_patterns = [
569
+ 'what are the other', 'what are the 3 other', 'what are all the topics',
570
+ 'what topics', 'what information do you have', 'what can you help with',
571
+ 'what documents', 'what subjects', 'what areas', 'list topics',
572
+ 'show me the topics', 'what else do you know', 'what other topics'
573
+ ]
574
+ is_topic_question = any(pattern in prompt_lower for pattern in topic_question_patterns)
575
+ if is_topic_question:
576
+ topics = get_document_topics()
577
+ if topics:
578
+ response = f"I have information on these topics:\n\n"
579
+ for i, topic in enumerate(topics, 1):
580
+ response += f"{i}. {topic}\n"
581
+ response += "\nWhich topic would you like to explore?"
582
+ return response, True
583
+ return None, False
584
+
585
+ def classify_query_type(prompt):
586
+ """Classify query type."""
587
+ prompt_lower = prompt.lower()
588
+ meta_patterns = [
589
+ 'what topics', 'what are the other', 'what information',
590
+ 'what can you help', 'what documents', 'list topics'
591
+ ]
592
+ if any(pattern in prompt_lower for pattern in meta_patterns):
593
+ return "meta_question"
594
+ if any(phrase in prompt_lower for phrase in ['summarize', 'summarise', 'summary', 'overview']):
595
+ return "summarization"
596
+ return "factual_question"
597
+
598
+ def validate_response_uses_documents(response, document_content):
599
+ """Check if response uses documents."""
600
+ if not document_content or not response:
601
+ return False
602
+ not_in_docs_phrases = [
603
+ "not in my uploaded documents", "not available in the provided documents",
604
+ "not covered in my documents", "this specific information isn't in"
605
+ ]
606
+ if any(phrase in response.lower() for phrase in not_in_docs_phrases):
607
+ return True
608
+ decline_phrases = ["cannot find", "not in the documents", "not mentioned"]
609
+ if any(phrase in response.lower() for phrase in decline_phrases):
610
+ return False
611
+ if not SAFETY_CONFIG['allow_general_knowledge']:
612
+ general_knowledge_flags = [
613
+ "generally", "typically", "usually", "commonly", "in general"
614
+ ]
615
+ if any(flag in response.lower() for flag in general_knowledge_flags):
616
+ return False
617
+ response_words = set(response.lower().split())
618
+ doc_words = set(document_content.lower().split())
619
+ common_words = {
620
+ 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by',
621
+ 'is', 'are', 'was', 'were', 'a', 'an', 'this', 'that', 'these', 'those',
622
+ 'can', 'will', 'would', 'should', 'could', 'may', 'might', 'must'
623
+ }
624
+ response_words -= common_words
625
+ doc_words -= common_words
626
+ if len(response_words) > 0:
627
+ overlap = len(response_words.intersection(doc_words))
628
+ overlap_ratio = overlap / len(response_words)
629
+ return overlap_ratio >= 0.15
630
+ return False
631
+
632
+ def build_conversation_context():
633
+ """Build conversation context."""
634
+ if len(st.session_state.messages) <= 1:
635
+ return ""
636
+ start_idx = 1 if st.session_state.messages[0]["role"] == "assistant" else 0
637
+ recent_messages = st.session_state.messages[start_idx:-MAX_CONVERSATION_HISTORY-1:-1]
638
+ recent_messages.reverse()
639
+ context_parts = []
640
+ for msg in recent_messages:
641
+ role = msg["role"]
642
+ content = clean_message_content(msg["content"])
643
+ if content:
644
+ if role == "user":
645
+ context_parts.append(f"User: {content}")
646
+ elif role == "assistant":
647
+ context_parts.append(f"Assistant: {content}")
648
+ return "\n".join(context_parts)
649
+
650
+ def format_text(text):
651
+ """Basic text formatting."""
652
+ replacements = {
653
+ 'alpha': 'α', 'beta': 'β', 'pi': 'π', 'sum': '∑',
654
+ 'leq': '≤', 'geq': '≥', 'neq': '≠', 'approx': '≈'
655
+ }
656
+ for latex, unicode_char in replacements.items():
657
+ text = text.replace('\\' + latex, unicode_char)
658
+ return text
659
+
660
+ def is_self_reference_request(query):
661
+ """Check if asking about previous response."""
662
+ query_lower = query.lower().strip()
663
+ self_reference_patterns = [
664
+ r'\b(your|that)\s+(answer|response|explanation)\b',
665
+ r'\bsummariz(e|ing)\s+(that|your|the)\s+(answer|response)\b',
666
+ r'\b(sum up|recap)\s+(that|your|the)\s+(answer|response)\b',
667
+ r'\bmake\s+(that|your|the)\s+(answer|response)\s+(shorter|brief|concise)\b',
668
+ r'\b(that|your)\s+(previous|last)\s+(answer|response)\b',
669
+ r'\bwhat\s+you\s+just\s+(said|explained|told)\b'
670
+ ]
671
+ simple_self_ref = [
672
+ "can you summarize", "can you summarise", "can you sum up",
673
+ "summarize that", "summarise that", "sum that up",
674
+ "make it shorter", "shorten it", "brief version",
675
+ "recap that", "condense that", "in summary"
676
+ ]
677
+ if any(re.search(pattern, query_lower) for pattern in self_reference_patterns):
678
+ return True
679
+ if any(phrase in query_lower for phrase in simple_self_ref):
680
+ return True
681
+ if query_lower in ["summarize", "summarise", "summary", "sum up", "recap", "brief"]:
682
+ return True
683
+ return False
684
+
685
+ def is_follow_up_request(query):
686
+ """Check if asking for more information."""
687
+ if is_self_reference_request(query):
688
+ return False
689
+ query_lower = query.lower()
690
+ follow_up_words = [
691
+ "more", "elaborate", "explain", "clarify", "expand", "further",
692
+ "continue", "what else", "tell me more", "go on", "details",
693
+ "can you", "could you", "please", "also", "additionally"
694
+ ]
695
+ return any(word in query_lower for word in follow_up_words)
696
+
697
+ def clean_model_output(raw_response):
698
+ """Clean model output."""
699
+ artifacts = [
700
+ "You are an educational assistant", "GUIDELINES:", "DOCUMENT CONTENT:",
701
+ "RECENT CONVERSATION:", "Current question:", "Based on the provided",
702
+ "According to the document", "STRICT RULES:", "Use ONLY", "Do NOT use",
703
+ "SAFETY GUIDELINES", "INSTRUCTIONS:"
704
+ ]
705
+ for artifact in artifacts:
706
+ raw_response = raw_response.replace(artifact, "").strip()
707
+ unwanted_patterns = [
708
+ r'I apologize if.*?[.!]?\s*',
709
+ r'I\'m sorry if.*?[.!]?\s*',
710
+ r'I\'m here to help with.*?[.!]?\s*',
711
+ ]
712
+ for pattern in unwanted_patterns:
713
+ raw_response = re.sub(pattern, '', raw_response, flags=re.IGNORECASE)
714
+ lines = raw_response.split("\n")
715
+ skip_patterns = [
716
+ "answer this question", "question:", "you are an", "be concise",
717
+ "i apologize", "i'm sorry"
718
+ ]
719
+ cleaned_lines = [
720
+ line for line in lines
721
+ if not any(line.lower().strip().startswith(pattern) for pattern in skip_patterns)
722
+ ]
723
+ cleaned_text = "\n".join(cleaned_lines)
724
+ cleaned_text = re.sub(r'\n{3,}', '\n\n', cleaned_text)
725
+ return cleaned_text.strip()
726
+
727
+ def create_system_message(has_docs, is_self_ref, document_content="", conversation_context="", last_response=""):
728
+ """Create system message with style adjustment."""
729
+ base_safety_rules = """
730
+ SAFETY GUIDELINES:
731
+ - Only provide helpful, educational, legal, and appropriate information
732
+ - Never provide instructions for illegal activities, violence, or harm
733
+ - Do not generate content that could be used to discriminate or harass
734
+ - Refuse inappropriate requests politely and suggest educational alternatives
735
+ """
736
+
737
+ # Adjust instructions based on response style
738
+ style_instructions = ""
739
+ if st.session_state.response_style == "Concise":
740
+ style_instructions = "\n- Be brief and direct. Provide concise answers without unnecessary details."
741
+ elif st.session_state.response_style == "Detailed":
742
+ style_instructions = "\n- Provide comprehensive, detailed explanations with examples and context."
743
+ else: # Balanced
744
+ style_instructions = "\n- Provide clear, balanced responses with appropriate detail."
745
+
746
+ if is_self_ref and last_response:
747
+ return f"""You are an educational assistant. The user is asking you to modify your previous response.
748
+
749
+ {base_safety_rules}
750
+
751
+ YOUR PREVIOUS RESPONSE:
752
+ {last_response}
753
+
754
+ CONTEXT:
755
+ {conversation_context}
756
+
757
+ INSTRUCTIONS:
758
+ - Provide the requested modification of your previous response
759
+ - Be concise and direct{style_instructions}"""
760
+ elif has_docs and SAFETY_CONFIG['allow_general_knowledge']:
761
+ return f"""You are an educational assistant that provides accurate, safe information.
762
+
763
+ {base_safety_rules}
764
+
765
+ CONTEXT:
766
+ {conversation_context}
767
+
768
+ DOCUMENT CONTENT:
769
+ {document_content}
770
+
771
+ STRATEGY:
772
+ 1. Check if the question can be answered using the documents
773
+ 2. If YES: Provide answer based on document content
774
+ 3. If NO but question is educational: State "This information isn't in my documents, but I can provide context:" then give general information
775
+ 4. If inappropriate: Politely decline
776
+ 5. Be direct, educational, and helpful{style_instructions}"""
777
+ elif has_docs:
778
+ return f"""You are an educational assistant focused on documents.
779
+
780
+ {base_safety_rules}
781
+
782
+ CONTEXT:
783
+ {conversation_context}
784
+
785
+ CONTENT:
786
+ {document_content}
787
+
788
+ INSTRUCTIONS:
789
+ - Use ONLY the provided content
790
+ - If not in documents, state this clearly
791
+ - Be direct and educational{style_instructions}"""
792
+ else:
793
+ return f"""You are an educational assistant.
794
+
795
+ {base_safety_rules}
796
+
797
+ CONTEXT:
798
+ {conversation_context}
799
+
800
+ The question doesn't match documents. If educational and appropriate, provide general information while being transparent.{style_instructions}"""
801
+
802
+ def generate_response_from_model(prompt, relevant_docs=None):
803
+ """Generate response with safety checks and style control."""
804
+ try:
805
+ model, tokenizer = get_model()
806
+
807
+ if model is None or tokenizer is None:
808
+ return "Error: Model could not be loaded."
809
+
810
+ is_safe, safety_message = check_question_safety(prompt)
811
+ if not is_safe:
812
+ return safety_message + generate_educational_alternative(prompt)
813
+
814
+ is_self_ref = is_self_reference_request(prompt)
815
+ conversation_context = build_conversation_context()
816
+
817
+ last_assistant_response = ""
818
+ if is_self_ref and len(st.session_state.messages) >= 2:
819
+ for msg in reversed(st.session_state.messages[:-1]):
820
+ if msg["role"] == "assistant":
821
+ last_assistant_response = clean_message_content(msg["content"])
822
+ break
823
+
824
+ document_content = ""
825
+ has_relevant_docs = False
826
+ if relevant_docs:
827
+ doc_texts = []
828
+ for doc in relevant_docs[:3]:
829
+ doc_texts.append(doc.page_content[:800])
830
+ document_content = "\n\n".join(doc_texts)
831
+ has_relevant_docs = len(doc_texts) > 0
832
+
833
+ system_message = create_system_message(
834
+ has_docs=has_relevant_docs,
835
+ is_self_ref=is_self_ref,
836
+ document_content=document_content,
837
+ conversation_context=conversation_context,
838
+ last_response=last_assistant_response
839
+ )
840
+
841
+ user_message = f"Question: {prompt}"
842
+
843
+ # Get style parameters
844
+ style_config = RESPONSE_STYLES[st.session_state.response_style]
845
+ temperature = style_config['temperature']
846
+ max_tokens = style_config['max_tokens']
847
+
848
+ # Determine device safely
849
+ try:
850
+ model_device = next(model.parameters()).device
851
+ except Exception as e:
852
+ print(f"⚠️ Could not get model device: {e}")
853
+ model_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
854
+
855
+ print(f"🔍 Using device: {model_device}")
856
+
857
+ # Try chat template first, fallback to manual formatting
858
+ try:
859
+ if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
860
+ messages = [
861
+ {"role": "system", "content": system_message},
862
+ {"role": "user", "content": user_message}
863
+ ]
864
+ inputs = tokenizer.apply_chat_template(
865
+ messages,
866
+ return_tensors="pt",
867
+ add_generation_prompt=True,
868
+ tokenize=True,
869
+ padding=False
870
+ )
871
+ inputs = inputs.to(model_device)
872
+ input_length = inputs.shape[1]
873
+ else:
874
+ raise AttributeError("No chat template available")
875
+
876
+ except (AttributeError, Exception) as e:
877
+ print(f"⚠️ Chat template failed, using fallback: {e}")
878
+ # Fallback to manual prompt formatting
879
+ formatted_prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant\n"
880
+ tokenized = tokenizer(formatted_prompt, return_tensors="pt", padding=False)
881
+
882
+ # Extract input_ids tensor from tokenizer output
883
+ inputs = tokenized["input_ids"].to(model_device)
884
+ input_length = inputs.shape[1]
885
+
886
+ # Generate
887
+ print(f"🔍 Generating with {input_length} input tokens...")
888
+
889
+ outputs = model.generate(
890
+ inputs,
891
+ max_new_tokens=max_tokens,
892
+ temperature=temperature,
893
+ top_p=0.8,
894
+ do_sample=True,
895
+ eos_token_id=tokenizer.eos_token_id,
896
+ pad_token_id=tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id,
897
+ repetition_penalty=1.1,
898
+ use_cache=True
899
+ )
900
+
901
+ # Decode output
902
+ if hasattr(outputs, 'shape'):
903
+ # outputs is a tensor
904
+ raw_response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
905
+ else:
906
+ # outputs might be in a different format
907
+ raw_response = tokenizer.decode(outputs[input_length:], skip_special_tokens=True)
908
+
909
+ print(f"✅ Generated {len(raw_response)} characters")
910
+ return raw_response.strip()
911
+
912
+ except Exception as e:
913
+ import traceback
914
+ error_details = traceback.format_exc()
915
+ print(f"❌ Full error traceback:")
916
+ print(error_details)
917
+ return f"Error generating response: {type(e).__name__}: {str(e)}"
918
+ def is_conversational_input(prompt):
919
+ """Check if input is conversational."""
920
+ prompt_lower = prompt.lower().strip()
921
+
922
+ # Remove trailing punctuation for matching
923
+ prompt_clean = re.sub(r'[!.?]+$', '', prompt_lower).strip()
924
+
925
+ # Exact match patterns
926
+ conversational_patterns = [
927
+ r'^(hi|hello|hey|greetings|howdy)[\s!.?]*$',
928
+ r'^(how\s+are\s+you|how\'s\s+it\s+going|what\'s\s+up|wassup)[\s!.?]*$',
929
+ r'^(good\s+morning|good\s+afternoon|good\s+evening|good\s+night)[\s!.?]*$',
930
+ r'^(thanks|thank\s+you|thx|ty|thank\s+u|thanx)[\s!.?]*$',
931
+ r'^(bye|goodbye|see\s+you|farewell|see\s+ya|later|cya)[\s!.?]*$',
932
+ r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$',
933
+ r'^(ok|okay|alright|sure|yes|yep|yeah|no|nope|got\s+it|understood|i\s+see)[\s!.?]*$',
934
+ r'^(cool|nice|great|awesome|perfect|fine|good)[\s!.?]*$',
935
+ r'^(hmm|hm|mhm|uh\s+huh|aha|oh|ooh|wow)[\s!.?]*$'
936
+ ]
937
+
938
+ # Check exact patterns first
939
+ if any(re.match(pattern, prompt_clean) for pattern in conversational_patterns):
940
+ return True
941
+
942
+ # Catch common farewell/thank you phrases that might have extra words
943
+ casual_phrases = [
944
+ 'thank you', 'thanks', 'thank u', 'thanx', 'amazing', 'fantastic',
945
+ 'have a good day', 'have a great day', 'have a nice day',
946
+ 'good day', 'great day', 'nice day',
947
+ 'goodbye', 'good bye', 'bye', 'see you', 'see ya',
948
+ 'take care', 'cheers'
949
+ ]
950
+
951
+ # Check if the entire prompt is just a casual phrase (even with punctuation)
952
+ for phrase in casual_phrases:
953
+ if prompt_clean == phrase or prompt_clean.startswith(phrase + ' '):
954
+ return True
955
+
956
+ return False
957
+
958
+ def generate_conversational_response(prompt):
959
+ """Generate conversational responses."""
960
+ prompt_lower = prompt.lower().strip()
961
+ document_topics = get_document_topics()
962
+ topic_hint = ""
963
+ if document_topics:
964
+ if len(document_topics) == 1:
965
+ topic_hint = f" I can help with {document_topics[0]}."
966
+ elif len(document_topics) == 2:
967
+ topic_hint = f" I can help with {document_topics[0]} and {document_topics[1]}."
968
+ else:
969
+ topic_hint = f" I can help with {document_topics[0]}, {document_topics[1]}, and more."
970
+
971
+ conversational_patterns = {
972
+ r'^(hi|hello|hey|greetings|howdy)[\s!.?]*$':
973
+ (f"Hello!{topic_hint} What would you like to learn?", True),
974
+ r'^(how\s+are\s+you|how\'s\s+it\s+going|what\'s\s+up)[\s!.?]*$':
975
+ (f"Ready to help!{topic_hint} What interests you?", True),
976
+ r'^(good\s+morning|good\s+afternoon|good\s+evening)[\s!.?]*$':
977
+ (f"{prompt.capitalize()}!{topic_hint} What would you like to explore?", True),
978
+ r'^(thanks|thank\s+you|thx|ty)[\s!.?]*$':
979
+ ("You're welcome! Anything else?", True),
980
+ r'^(bye|goodbye|see\s+you|farewell)[\s!.?]*$':
981
+ ("Goodbye!", False),
982
+ r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$':
983
+ ("Conversation cleared.", True),
984
+ r'^(ok|okay|alright|sure|got\s+it|understood|i\s+see)[\s!.?]*$':
985
+ ("What else can I help with?", True),
986
+ r'^(yes|yep|yeah)[\s!.?]*$':
987
+ ("What would you like to explore?", True),
988
+ r'^(no|nope)[\s!.?]*$':
989
+ ("Feel free to ask anytime.", True),
990
+ r'^(cool|nice|great|awesome|perfect)[\s!.?]*$':
991
+ ("What else?", True),
992
+ r'^(fine|good)[\s!.?]*$':
993
+ ("What's next?", True),
994
+ r'^(hmm|hm|mhm|uh\s+huh|aha|oh|ooh|wow)[\s!.?]*$':
995
+ ("Something specific you'd like to explore?", True)
996
+ }
997
+
998
+ for pattern, (response, continue_flag) in conversational_patterns.items():
999
+ if re.match(pattern, prompt_lower):
1000
+ return response, continue_flag
1001
+
1002
+ return f"I'm here to help.{topic_hint} What interests you?", True
1003
+
1004
+ def generate_follow_up_question(context, conversation_length, prompt=None):
1005
+ """Generate follow-up question."""
1006
+ if prompt and is_self_reference_request(prompt):
1007
+ return None
1008
+ context_lower = context.lower()
1009
+ if "process" in context_lower or "step" in context_lower:
1010
+ return "What are the key steps?"
1011
+ elif "method" in context_lower or "approach" in context_lower:
1012
+ return "How is this applied in practice?"
1013
+ elif "benefit" in context_lower or "advantage" in context_lower:
1014
+ return "What challenges might arise?"
1015
+ simple_questions = [
1016
+ "What interests you most?",
1017
+ "Would you like to explore related concepts?",
1018
+ "Need more details?"
1019
+ ]
1020
+ return simple_questions[conversation_length % len(simple_questions)]
1021
+
1022
+ def process_query(prompt, context_docs):
1023
+ """Process query with enhanced features."""
1024
+ is_safe, safety_message = check_question_safety(prompt)
1025
+ if not is_safe:
1026
+ return safety_message + generate_educational_alternative(prompt), None, False, None
1027
+
1028
+ if is_conversational_input(prompt):
1029
+ response, should_continue = generate_conversational_response(prompt)
1030
+ reset_pattern = r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$'
1031
+ if re.match(reset_pattern, prompt.lower().strip()):
1032
+ return response, None, True, None
1033
+ return response, None, False, None
1034
+
1035
+ query_type = classify_query_type(prompt)
1036
+ if query_type == "meta_question":
1037
+ response, handled = handle_topic_questions(prompt)
1038
+ if handled:
1039
+ return response, None, False, None
1040
+
1041
+ is_self_ref = is_self_reference_request(prompt)
1042
+ if is_self_ref:
1043
+ raw_response = generate_response_from_model(prompt, relevant_docs=None)
1044
+ clean_response = clean_model_output(raw_response)
1045
+ clean_response = format_text(clean_response)
1046
+ return clean_response, None, False, None
1047
+
1048
+ if needs_pronoun_resolution(prompt):
1049
+ expanded_prompt, was_expanded = detect_pronouns_and_resolve(prompt, st.session_state.messages)
1050
+ if was_expanded:
1051
+ prompt = expanded_prompt
1052
+ st.info(f"Understood: '{prompt}'")
1053
+
1054
+ is_followup = is_follow_up_request(prompt)
1055
+ #relevant_docs, similarity_scores = check_document_relevance(prompt, context_docs, min_similarity=MIN_SIMILARITY_THRESHOLD)
1056
+ relevant_docs = context_docs # Chroma already ranked these by relevance
1057
+
1058
+ raw_response = generate_response_from_model(prompt, relevant_docs if relevant_docs else None)
1059
+ clean_response = clean_model_output(raw_response)
1060
+ clean_response = format_text(clean_response)
1061
+
1062
+ sources = set()
1063
+ used_documents = False
1064
+ safety_decline_phrases = [
1065
+ "keep conversations appropriate", "focused on educational topics",
1066
+ "respectful and focused", "designed to support ethical learning"
1067
+ ]
1068
+ is_safety_decline = any(phrase in clean_response.lower() for phrase in safety_decline_phrases)
1069
+
1070
+ if not is_safety_decline and relevant_docs:
1071
+ if any(phrase in clean_response.lower() for phrase in [
1072
+ "according to the document", "the document shows", "based on the provided",
1073
+ "from the document", "the text states", "as mentioned in"
1074
+ ]):
1075
+ used_documents = True
1076
+ for doc in relevant_docs:
1077
+ if hasattr(doc, "metadata") and "source" in doc.metadata:
1078
+ sources.add(doc.metadata["source"])
1079
+ elif any(phrase in clean_response.lower() for phrase in [
1080
+ "not in my uploaded documents", "not available in the provided documents",
1081
+ "not covered in my documents", "this specific information isn't in"
1082
+ ]):
1083
+ used_documents = False
1084
+ else:
1085
+ document_content = "\n\n".join([doc.page_content for doc in relevant_docs[:3]])
1086
+ if validate_response_uses_documents(clean_response, document_content):
1087
+ used_documents = True
1088
+ for doc in relevant_docs:
1089
+ if hasattr(doc, "metadata") and "source" in doc.metadata:
1090
+ sources.add(doc.metadata["source"])
1091
+
1092
+ if not is_followup and not is_safety_decline and len(st.session_state.messages) % 3 == 0:
1093
+ follow_up = generate_follow_up_question(clean_response, len(st.session_state.messages), prompt)
1094
+ if follow_up:
1095
+ clean_response += f"\n\n{follow_up}"
1096
+
1097
+ if used_documents and sources and not is_safety_decline:
1098
+ clean_response += f"\n\nSource: {', '.join(sorted(sources))}"
1099
+
1100
+ return clean_response, ", ".join(sorted(sources)) if sources else None, False, None
1101
+
1102
+ # ====== STREAMLIT INTERFACE ======
1103
+
1104
+ # Custom CSS for better visual appearance
1105
+ st.markdown("""
1106
+ <style>
1107
+ /* Message bubbles - different colors for user vs assistant */
1108
+ [data-testid="stChatMessageContent"] {
1109
+ padding: 1rem;
1110
+ border-radius: 0.5rem;
1111
+ }
1112
+
1113
+ /* User messages - light blue background */
1114
+ [data-testid="stChatMessage"][data-testid*="user"] {
1115
+ background-color: #E3F2FD;
1116
+ }
1117
+
1118
+ /* Assistant messages - light gray background */
1119
+ [data-testid="stChatMessage"]:not([data-testid*="user"]) {
1120
+ background-color: #F5F5F5;
1121
+ }
1122
+
1123
+ /* Sidebar sections styling */
1124
+ .stSidebar [data-testid="stMarkdownContainer"] {
1125
+ background-color: #FAFAFA;
1126
+ padding: 0.5rem;
1127
+ border-radius: 0.3rem;
1128
+ margin-bottom: 0.5rem;
1129
+ }
1130
+
1131
+ /* Settings section - light purple */
1132
+ .stSidebar .element-container:has(> [data-testid="stSelectbox"]) {
1133
+ background-color: #F3E5F5;
1134
+ padding: 1rem;
1135
+ border-radius: 0.5rem;
1136
+ margin-bottom: 1rem;
1137
+ }
1138
+
1139
+ /* Documents section header styling */
1140
+ .stSidebar h3 {
1141
+ color: #5E35B1;
1142
+ font-size: 1rem;
1143
+ font-weight: 600;
1144
+ }
1145
+
1146
+ /* Input area focus effect */
1147
+ [data-testid="stChatInput"] textarea:focus {
1148
+ background-color: #F1F8F4;
1149
+ border-color: #4CAF50;
1150
+ }
1151
+
1152
+ /* Info messages - light cyan for pronoun resolution */
1153
+ .stAlert[data-baseweb="notification"] {
1154
+ background-color: #E0F7FA;
1155
+ }
1156
+
1157
+ /* Success messages */
1158
+ [data-testid="stAlert"][kind="success"] {
1159
+ background-color: #E8F5E9;
1160
+ }
1161
+
1162
+ /* Error messages keep default red but soften */
1163
+ [data-testid="stAlert"][kind="error"] {
1164
+ background-color: #FFEBEE;
1165
+ }
1166
+
1167
+ /* Buttons styling */
1168
+ .stButton button {
1169
+ border-radius: 0.5rem;
1170
+ font-weight: 500;
1171
+ transition: all 0.3s ease;
1172
+ }
1173
+
1174
+ .stButton button:hover {
1175
+ transform: translateY(-2px);
1176
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
1177
+ }
1178
+
1179
+ /* Spinner text color */
1180
+ .stSpinner > div {
1181
+ border-top-color: #5E35B1 !important;
1182
+ }
1183
+ </style>
1184
+ """, unsafe_allow_html=True)
1185
+
1186
+ st.title(APP_TITLE)
1187
+
1188
+ # Sidebar
1189
+ with st.sidebar:
1190
+ st.title("System")
1191
+
1192
+ if st.button("Logout", use_container_width=True):
1193
+ st.session_state.authenticated = False
1194
+ st.session_state.messages = []
1195
+ st.session_state.conversation_id = 0
1196
+ st.rerun()
1197
+
1198
+ st.markdown("---")
1199
+ st.subheader("Settings")
1200
+
1201
+ # Response style selector
1202
+ response_style = st.selectbox(
1203
+ "Response Style",
1204
+ ["Balanced", "Concise", "Detailed"],
1205
+ index=["Balanced", "Concise", "Detailed"].index(st.session_state.response_style),
1206
+ help="Control the length and detail of responses"
1207
+ )
1208
+
1209
+ # Update session state if changed
1210
+ if response_style != st.session_state.response_style:
1211
+ st.session_state.response_style = response_style
1212
+ st.rerun()
1213
+
1214
+ st.markdown("---")
1215
+ st.write("**Documents:**")
1216
+ for pdf in PDF_FILES:
1217
+ st.write(f"• {os.path.basename(pdf)}")
1218
+
1219
+ # Initialize welcome message
1220
+ if not st.session_state.messages:
1221
+ document_topics = get_document_topics()
1222
+ if document_topics:
1223
+ if len(document_topics) == 1:
1224
+ topic_preview = f"Hello, we can talk about **{document_topics[0]}**, exploring together interesting ideas and reflecting upon our shared challenges, using our curated knowledge base."
1225
+ elif len(document_topics) == 2:
1226
+ topic_preview = f"Hello, we can talk about **{document_topics[0]}** and **{document_topics[1]}**, exploring together interesting ideas and reflecting upon our shared challenges, using our curated knowledge base."
1227
+ else:
1228
+ topic_list = ", ".join([f"**{topic}**" for topic in document_topics[:-1]])
1229
+ last_topic = f"**{document_topics[-1]}**"
1230
+ topic_preview = f"Hello, we can talk about {topic_list}, and {last_topic}, exploring together interesting ideas and reflecting upon our shared challenges, using our curated knowledge base."
1231
+ else:
1232
+ topic_preview = "Let's explore interesting ideas together using our curated knowledge base."
1233
+
1234
+ welcome_msg = topic_preview
1235
+ st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
1236
+
1237
+ # Clear conversation button
1238
+ col1, col2 = st.columns([4, 1])
1239
+ with col2:
1240
+ if st.button("New Conversation", use_container_width=True):
1241
+ st.session_state.conversation_id += 1
1242
+ st.session_state.messages = []
1243
+ document_topics = get_document_topics()
1244
+ if document_topics:
1245
+ if len(document_topics) == 1:
1246
+ topic_preview = f"Hello, we can talk about **{document_topics[0]}**, exploring together interesting ideas and reflecting upon our shared challenges, using our curated knowledge base."
1247
+ elif len(document_topics) <= 3:
1248
+ topic_list = " and ".join([f"**{topic}**" for topic in document_topics])
1249
+ topic_preview = f"Hello, we can talk about {topic_list}, exploring together interesting ideas and reflecting upon our shared challenges, using our curated knowledge base."
1250
+ else:
1251
+ topic_list = ", ".join([f"**{topic}**" for topic in document_topics[:2]])
1252
+ topic_preview = f"Hello, we can talk about {topic_list}, and more, exploring together interesting ideas and reflecting upon our shared challenges, using our curated knowledge base."
1253
+ else:
1254
+ topic_preview = "Let's explore interesting ideas together using our curated knowledge base."
1255
+ welcome_msg = topic_preview
1256
+ st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
1257
+ st.rerun()
1258
+
1259
+ # ← CHANGED: Use get_retriever() instead of checking if retriever exists
1260
+ retriever = get_retriever()
1261
+
1262
+ if retriever:
1263
+ # Display messages with copy button for assistant responses
1264
+ for idx, message in enumerate(st.session_state.messages):
1265
+ with st.chat_message(message["role"]):
1266
+ st.markdown(message["content"])
1267
+
1268
+ # Add copy button for assistant messages
1269
+ if message["role"] == "assistant":
1270
+ button_id = f"copy_btn_{idx}_{st.session_state.conversation_id}"
1271
+ create_copy_button(message["content"], button_id)
1272
+
1273
+ # User input
1274
+ if prompt := st.chat_input("What would you like to learn?"):
1275
+ st.session_state.messages.append({"role": "user", "content": prompt})
1276
+ with st.chat_message("user"):
1277
+ st.markdown(prompt)
1278
+
1279
+ with st.chat_message("assistant"):
1280
+ try:
1281
+ # Only retrieve documents if NOT conversational
1282
+ if is_conversational_input(prompt):
1283
+ retrieved_docs = None
1284
+ else:
1285
+ retrieved_docs = retriever.invoke(prompt)
1286
+
1287
+ answer, sources, should_reset, new_follow_up = process_query(prompt, retrieved_docs)
1288
+ if should_reset:
1289
+ st.session_state.conversation_id += 1
1290
+ st.session_state.messages = []
1291
+ st.session_state.messages.append({"role": "assistant", "content": answer})
1292
+ st.rerun()
1293
+
1294
+ st.session_state.messages.append({"role": "assistant", "content": answer})
1295
+ st.markdown(answer)
1296
+
1297
+ # Add copy button for the new response
1298
+ button_id = f"copy_btn_new_{st.session_state.conversation_id}_{len(st.session_state.messages)}"
1299
+ create_copy_button(answer, button_id)
1300
+ except Exception as e:
1301
+ error_msg = f"Error: {str(e)}"
1302
+ st.error(error_msg)
1303
+ st.session_state.messages.append({"role": "assistant", "content": error_msg})
1304
+ else:
1305
+ st.error("Failed to load document retrieval system.")
requirements (2).txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ huggingface_hub
3
+ langchain==0.2.16
4
+ langchain-community
5
+ langchain-text-splitters
6
+ langchain_huggingface
7
+ faiss-cpu
8
+ pypdf
9
+ sentence-transformers
10
+ transformers
11
+ accelerate>=0.26.0
12
+ bitsandbytes>=0.46.1
13
+ torch>=2.5.0
runtime (1).txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python-3.11