Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Universal RAG PDF Chatbot with Enhanced Safety Checks and Improved Context Management - COMPLETE UPDATED VERSION WITH PASSWORD PROTECTION
|
| 3 |
-
|
| 4 |
-
This is a general-purpose RAG (Retrieval-Augmented Generation) chatbot that can work with any set of PDF documents.
|
| 5 |
-
It includes comprehensive safety checks and can provide educational responses even when information isn't in the documents.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
import hashlib
|
| 9 |
import numpy as np
|
| 10 |
import os
|
|
@@ -25,16 +18,13 @@ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
|
| 25 |
# ====== CONFIGURATION SECTION ======
|
| 26 |
APP_TITLE = "Educational PDF Chatbot"
|
| 27 |
APP_LAYOUT = "wide"
|
| 28 |
-
MODEL_NAME="Qwen/Qwen2.5-14B-Instruct"
|
| 29 |
-
#MODEL_NAME = "mistralai/Ministral-8B-Instruct-2410"
|
| 30 |
-
|
| 31 |
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
|
|
|
| 32 |
CHUNK_SIZE = 2000
|
| 33 |
CHUNK_OVERLAP = 300
|
| 34 |
SEARCH_K = 7
|
| 35 |
MIN_SIMILARITY_THRESHOLD = 0.1
|
| 36 |
-
MAX_NEW_TOKENS = 500
|
| 37 |
-
TEMPERATURE = 0.1
|
| 38 |
MAX_CONVERSATION_HISTORY = 6
|
| 39 |
|
| 40 |
PDF_SEARCH_PATHS = [
|
|
@@ -44,150 +34,98 @@ PDF_SEARCH_PATHS = [
|
|
| 44 |
"pdfs/*.pdf"
|
| 45 |
]
|
| 46 |
|
| 47 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
SAFETY_CONFIG = {
|
| 49 |
-
'enable_strict_mode': False,
|
| 50 |
-
'educational_alternatives': True,
|
| 51 |
-
'allow_general_knowledge': True
|
| 52 |
}
|
| 53 |
|
| 54 |
-
# ====== PASSWORD AUTHENTICATION CONFIGURATION ======
|
| 55 |
-
# Password can be set in Streamlit secrets or environment variable
|
| 56 |
CHATBOT_PASSWORD = st.secrets.get("CHATBOT_PASSWORD", os.getenv("CHATBOT_PASSWORD", "edu123"))
|
| 57 |
|
| 58 |
# ====== END CONFIGURATION SECTION ======
|
| 59 |
|
| 60 |
-
# Set environment variables
|
| 61 |
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 62 |
os.environ["HF_HUB_DISABLE_EXPERIMENTAL_WARNING"] = "1"
|
| 63 |
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "0"
|
| 64 |
|
| 65 |
-
# NumPy compatibility
|
| 66 |
np.float_ = np.float64
|
| 67 |
-
|
| 68 |
-
# Streamlit Page Config
|
| 69 |
st.set_page_config(page_title=APP_TITLE, layout=APP_LAYOUT)
|
| 70 |
|
| 71 |
-
# ======
|
| 72 |
def check_password():
|
| 73 |
"""Check password and manage authentication."""
|
| 74 |
-
|
| 75 |
-
# Initialize authentication state
|
| 76 |
if "authenticated" not in st.session_state:
|
| 77 |
st.session_state.authenticated = False
|
| 78 |
-
|
| 79 |
if "login_attempts" not in st.session_state:
|
| 80 |
st.session_state.login_attempts = 0
|
| 81 |
|
| 82 |
-
# If already authenticated, return True
|
| 83 |
if st.session_state.authenticated:
|
| 84 |
return True
|
| 85 |
|
| 86 |
-
# Display login screen
|
| 87 |
st.markdown("""
|
| 88 |
<div style='text-align: center; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 2rem;'>
|
| 89 |
<h1 style='color: white; margin-bottom: 1rem;'>🔒 Educational PDF Chatbot</h1>
|
| 90 |
-
<p style='color: white; font-size: 1.1em;'>
|
| 91 |
</div>
|
| 92 |
""", unsafe_allow_html=True)
|
| 93 |
|
| 94 |
-
# Check for too many failed attempts
|
| 95 |
if st.session_state.login_attempts >= 5:
|
| 96 |
-
st.error("Too many failed
|
| 97 |
-
st.info("If you continue to have trouble, please contact the administrator.")
|
| 98 |
st.stop()
|
| 99 |
|
| 100 |
-
# Login form
|
| 101 |
with st.form("login_form"):
|
| 102 |
-
st.subheader("
|
| 103 |
-
password = st.text_input(
|
| 104 |
-
|
| 105 |
-
type="password",
|
| 106 |
-
placeholder="Enter your access password...",
|
| 107 |
-
help="Enter the password provided to you for accessing this educational chatbot"
|
| 108 |
-
)
|
| 109 |
-
submit_button = st.form_submit_button("🚀 Access Chatbot", use_container_width=True)
|
| 110 |
|
| 111 |
if submit_button:
|
| 112 |
if password == CHATBOT_PASSWORD:
|
| 113 |
st.session_state.authenticated = True
|
| 114 |
st.session_state.login_attempts = 0
|
| 115 |
-
st.success("✅ Access granted! Loading your educational assistant...")
|
| 116 |
st.rerun()
|
| 117 |
else:
|
| 118 |
st.session_state.login_attempts += 1
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
st.error(f"❌ Incorrect password. Attempts remaining: {remaining_attempts}")
|
| 123 |
else:
|
| 124 |
-
st.error("
|
| 125 |
-
|
| 126 |
-
# Additional information in sidebar
|
| 127 |
-
st.sidebar.markdown("""
|
| 128 |
-
### 📋 Access Information
|
| 129 |
-
|
| 130 |
-
**To access this educational chatbot:**
|
| 131 |
-
- Enter the provided access password
|
| 132 |
-
- Maximum 5 attempts allowed
|
| 133 |
-
- Contact administrator if you need help
|
| 134 |
-
|
| 135 |
-
**Features available after login:**
|
| 136 |
-
- PDF document analysis
|
| 137 |
-
- Educational Q&A system
|
| 138 |
-
- Context-aware responses
|
| 139 |
-
- Safe content filtering
|
| 140 |
-
- Conversation management
|
| 141 |
-
""")
|
| 142 |
-
|
| 143 |
-
st.sidebar.markdown("---")
|
| 144 |
-
st.sidebar.info("🛡️ This system includes comprehensive safety features and educational content filtering.")
|
| 145 |
-
|
| 146 |
return False
|
| 147 |
|
| 148 |
-
# Check authentication before loading the rest of the application
|
| 149 |
if not check_password():
|
| 150 |
st.stop()
|
| 151 |
|
| 152 |
-
# ======
|
| 153 |
-
|
| 154 |
-
# Add logout functionality in sidebar
|
| 155 |
-
st.sidebar.markdown("---")
|
| 156 |
-
st.sidebar.success("✅ Access Authorized")
|
| 157 |
-
st.sidebar.write("Welcome to your educational assistant!")
|
| 158 |
-
|
| 159 |
-
if st.sidebar.button("🚪 Logout", use_container_width=True):
|
| 160 |
-
st.session_state.authenticated = False
|
| 161 |
-
st.session_state.messages = []
|
| 162 |
-
st.session_state.conversation_id = 0
|
| 163 |
-
st.success("👋 Successfully logged out!")
|
| 164 |
-
st.rerun()
|
| 165 |
-
|
| 166 |
-
# Initialize essential session state variables only
|
| 167 |
if "messages" not in st.session_state:
|
| 168 |
st.session_state.messages = []
|
| 169 |
-
|
| 170 |
if "conversation_id" not in st.session_state:
|
| 171 |
st.session_state.conversation_id = 0
|
| 172 |
-
|
| 173 |
if "model_loaded" not in st.session_state:
|
| 174 |
st.session_state.model_loaded = False
|
|
|
|
|
|
|
| 175 |
|
| 176 |
-
#
|
| 177 |
HF_API_KEY = st.secrets.get("HF_TOKEN", os.getenv("HF_TOKEN"))
|
| 178 |
|
| 179 |
if HF_API_KEY:
|
| 180 |
HfFolder.save_token(HF_API_KEY)
|
| 181 |
|
| 182 |
if not HF_API_KEY:
|
| 183 |
-
st.error("Hugging Face API key is missing
|
| 184 |
st.stop()
|
| 185 |
|
| 186 |
@st.cache_resource
|
| 187 |
def load_quantized_model():
|
| 188 |
-
"""Load model with 4-bit quantization
|
| 189 |
try:
|
| 190 |
-
# Configure 4-bit quantization
|
| 191 |
quantization_config = BitsAndBytesConfig(
|
| 192 |
load_in_4bit=True,
|
| 193 |
bnb_4bit_compute_dtype=torch.float16,
|
|
@@ -217,15 +155,13 @@ def load_quantized_model():
|
|
| 217 |
trust_remote_code=True,
|
| 218 |
)
|
| 219 |
|
| 220 |
-
st.success("Quantized model loaded correctly")
|
| 221 |
return model, tokenizer
|
| 222 |
except Exception as e:
|
| 223 |
-
st.error(f"Error loading
|
| 224 |
return None, None
|
| 225 |
|
| 226 |
# Load model
|
| 227 |
if not st.session_state.model_loaded:
|
| 228 |
-
st.info("Initializing model... This may take a few minutes on first load.")
|
| 229 |
with st.spinner("Loading model..."):
|
| 230 |
model, tokenizer = load_quantized_model()
|
| 231 |
if model is not None:
|
|
@@ -235,95 +171,68 @@ else:
|
|
| 235 |
|
| 236 |
@st.cache_resource
|
| 237 |
def load_sentence_model():
|
| 238 |
-
"""Load sentence transformer model
|
| 239 |
try:
|
| 240 |
-
st.info(f"Loading sentence transformer model: {EMBEDDING_MODEL}")
|
| 241 |
return SentenceTransformer(EMBEDDING_MODEL, token=HF_API_KEY)
|
| 242 |
except Exception as e:
|
| 243 |
-
st.warning(f"Error loading sentence model: {str(e)}")
|
| 244 |
-
st.info("Using fallback sentence model...")
|
| 245 |
try:
|
| 246 |
return SentenceTransformer("sentence-transformers/all-mpnet-base-v2", token=HF_API_KEY)
|
| 247 |
except Exception as e2:
|
| 248 |
-
st.error(f"Fallback model failed: {str(e2)}")
|
| 249 |
-
|
| 250 |
class SimpleEmbedder:
|
| 251 |
def encode(self, texts, convert_to_tensor=True):
|
| 252 |
-
import numpy as np
|
| 253 |
-
import torch
|
| 254 |
-
|
| 255 |
if isinstance(texts, str):
|
| 256 |
texts = [texts]
|
| 257 |
-
|
| 258 |
embeddings = []
|
| 259 |
for text in texts:
|
| 260 |
words = set(text.lower().split())
|
| 261 |
embedding = np.zeros(384)
|
| 262 |
-
|
| 263 |
for i, word in enumerate(words):
|
| 264 |
for j, char in enumerate(word):
|
| 265 |
if i < 384:
|
| 266 |
embedding[i] = ord(char) / 255.0
|
| 267 |
-
|
| 268 |
embeddings.append(embedding)
|
| 269 |
-
|
| 270 |
if convert_to_tensor:
|
| 271 |
return torch.tensor(embeddings)
|
| 272 |
return np.array(embeddings)
|
| 273 |
-
|
| 274 |
return SimpleEmbedder()
|
| 275 |
|
| 276 |
sentence_model = load_sentence_model()
|
| 277 |
|
| 278 |
def check_question_safety(question):
|
| 279 |
-
"""
|
| 280 |
-
Comprehensive safety check for questions - FIXED to avoid false positives
|
| 281 |
-
Returns: (is_safe, safety_message)
|
| 282 |
-
"""
|
| 283 |
question_lower = question.lower().strip()
|
| 284 |
|
| 285 |
-
# Check for profanity with more precise patterns to avoid false positives
|
| 286 |
profanity_patterns = [
|
| 287 |
r'\bfuck\b', r'\bfucking\b', r'\bfucked\b', r'\bfucker\b',
|
| 288 |
r'\bshit\b', r'\bshitty\b', r'\bshitting\b',
|
| 289 |
r'\bbitch\b', r'\bbitching\b', r'\bbitchy\b',
|
| 290 |
-
r'\bass\b(?!\w)', r'\basshole\b',
|
| 291 |
-
r'\bdamn\b(?!\w)',
|
| 292 |
r'\bcrap\b', r'\bcrappy\b'
|
| 293 |
-
# Note: Removed "hell" pattern as it creates false positives with "hello", "shell", etc.
|
| 294 |
]
|
| 295 |
|
| 296 |
-
# Only flag if profanity is used inappropriately (not in compound words)
|
| 297 |
for pattern in profanity_patterns:
|
| 298 |
if re.search(pattern, question_lower):
|
| 299 |
-
return False, "I'd prefer to keep our conversation respectful and
|
| 300 |
|
| 301 |
-
# Define inappropriate content patterns
|
| 302 |
unsafe_patterns = [
|
| 303 |
-
# Violence and harm - more specific patterns
|
| 304 |
r'\b(kill|murder|hurt|harm|attack|violence|weapon|bomb|suicide)\b',
|
| 305 |
r'\bself[\s\-]harm\b',
|
| 306 |
-
# Illegal activities
|
| 307 |
r'\b(illegal\s+drugs|hack\s+into|steal\s+from|fraud|piracy|money\s+laundering)\b',
|
| 308 |
r'\bhow\s+to\s+(hack|steal|forge|counterfeit)\b',
|
| 309 |
-
# Inappropriate personal information requests
|
| 310 |
r'\b(personal\s+address|phone\s+number|social\s+security|password|credit\s+card)\b',
|
| 311 |
r'\bprivate\s+information\b',
|
| 312 |
-
# Hate speech indicators - more specific
|
| 313 |
r'\b(hate\s+speech|racist\s+jokes|discrimination\s+against|offensive\s+slur)\b',
|
| 314 |
r'\bextremist\s+(content|views|ideology)\b',
|
| 315 |
-
# Adult content - expanded patterns
|
| 316 |
r'\b(sexual\s+content|pornographic|explicit\s+content|adult\s+material)\b',
|
| 317 |
-
r'\b(sexy|erotic|intimate|adult\s+humor)\b',
|
| 318 |
r'\b(sexual\s+joke|dirty\s+joke|adult\s+joke)\b'
|
| 319 |
]
|
| 320 |
|
| 321 |
-
# Check for unsafe patterns
|
| 322 |
for pattern in unsafe_patterns:
|
| 323 |
if re.search(pattern, question_lower):
|
| 324 |
-
return False, "I keep conversations appropriate and
|
| 325 |
|
| 326 |
-
# Educational context specific checks - more precise
|
| 327 |
educational_inappropriate = [
|
| 328 |
'how to cheat on', 'academic dishonesty', 'plagiarism methods', 'fake certificates',
|
| 329 |
'exam answers for', 'homework answers for', 'cheat codes for', 'bypass security'
|
|
@@ -331,71 +240,48 @@ def check_question_safety(question):
|
|
| 331 |
|
| 332 |
for phrase in educational_inappropriate:
|
| 333 |
if phrase in question_lower:
|
| 334 |
-
return False, "I'm designed to support ethical learning
|
| 335 |
-
|
| 336 |
-
# Additional strict mode checks
|
| 337 |
-
if SAFETY_CONFIG['enable_strict_mode']:
|
| 338 |
-
strict_patterns = [
|
| 339 |
-
r'\b(controversial\s+opinion|sensitive\s+political|political\s+bias)\b'
|
| 340 |
-
]
|
| 341 |
-
for pattern in strict_patterns:
|
| 342 |
-
if re.search(pattern, question_lower):
|
| 343 |
-
return False, "I focus on educational content and prefer to avoid potentially controversial topics."
|
| 344 |
|
| 345 |
return True, ""
|
| 346 |
|
| 347 |
def generate_educational_alternative(declined_topic):
|
| 348 |
-
"""Provide educational alternatives
|
| 349 |
if not SAFETY_CONFIG['educational_alternatives']:
|
| 350 |
return ""
|
| 351 |
|
| 352 |
alternatives = {
|
| 353 |
-
'violence': "I can help with conflict resolution, peace studies, or
|
| 354 |
-
'illegal': "I can provide information about legal systems, ethics, or policy studies
|
| 355 |
'harm': "I can help with safety education, health information, or wellness topics.",
|
| 356 |
-
'academic_dishonesty': "I can help you understand the topic better
|
| 357 |
-
'weapons': "I can discuss historical warfare, security studies, or peace and conflict resolution instead.",
|
| 358 |
-
'drugs': "I can provide information about pharmacology, public health, or substance abuse prevention programs."
|
| 359 |
}
|
| 360 |
|
| 361 |
for key, alternative in alternatives.items():
|
| 362 |
if key in declined_topic.lower():
|
| 363 |
-
return f"\n\
|
| 364 |
|
| 365 |
-
return "\n\
|
| 366 |
|
| 367 |
def clean_document_text(text):
|
| 368 |
-
"""Clean document text
|
| 369 |
if not text:
|
| 370 |
return text
|
| 371 |
-
|
| 372 |
import unicodedata
|
| 373 |
-
|
| 374 |
try:
|
| 375 |
text = unicodedata.normalize('NFKD', text)
|
| 376 |
except:
|
| 377 |
pass
|
| 378 |
-
|
| 379 |
-
# Remove Arabic characters specifically
|
| 380 |
text = re.sub(r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]', '', text)
|
| 381 |
-
|
| 382 |
-
# Keep only ASCII and common European characters
|
| 383 |
text = re.sub(r'[^\x00-\x7F\u00C0-\u00FF]', '', text)
|
| 384 |
-
|
| 385 |
-
# Clean up whitespace
|
| 386 |
text = re.sub(r'\s+', ' ', text)
|
| 387 |
-
|
| 388 |
return text.strip()
|
| 389 |
|
| 390 |
def get_pdf_files():
|
| 391 |
-
"""
|
| 392 |
pdf_files = []
|
| 393 |
-
|
| 394 |
for search_path in PDF_SEARCH_PATHS:
|
| 395 |
found_files = glob.glob(search_path)
|
| 396 |
pdf_files.extend(found_files)
|
| 397 |
-
|
| 398 |
-
# Remove duplicates and sort
|
| 399 |
pdf_files = list(set(pdf_files))
|
| 400 |
pdf_files.sort()
|
| 401 |
return pdf_files
|
|
@@ -403,94 +289,67 @@ def get_pdf_files():
|
|
| 403 |
PDF_FILES = get_pdf_files()
|
| 404 |
|
| 405 |
if not PDF_FILES:
|
| 406 |
-
st.error("No PDF files found.
|
| 407 |
-
st.info("The app will look for PDF files in these locations:")
|
| 408 |
-
for path in PDF_SEARCH_PATHS:
|
| 409 |
-
st.info(f"- {path}")
|
| 410 |
st.stop()
|
| 411 |
-
else:
|
| 412 |
-
st.success(f"Found {len(PDF_FILES)} PDF file(s): {', '.join([os.path.basename(f) for f in PDF_FILES])}")
|
| 413 |
|
| 414 |
@st.cache_resource
|
| 415 |
def load_and_index_pdfs():
|
| 416 |
-
"""Load and process
|
| 417 |
try:
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
# Create embeddings
|
| 445 |
-
try:
|
| 446 |
-
embeddings = HuggingFaceEmbeddings(
|
| 447 |
-
model_name=EMBEDDING_MODEL,
|
| 448 |
-
model_kwargs={"token": HF_API_KEY}
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
# Test embeddings
|
| 452 |
-
test_embed = embeddings.embed_query("test")
|
| 453 |
-
if not test_embed or len(test_embed) == 0:
|
| 454 |
-
raise ValueError("Embedding model returned empty embeddings")
|
| 455 |
-
|
| 456 |
-
except Exception as embed_error:
|
| 457 |
-
st.warning(f"Primary embedding model failed: {str(embed_error)}")
|
| 458 |
-
|
| 459 |
-
# Fallback embedding class
|
| 460 |
-
from langchain.embeddings.base import Embeddings
|
| 461 |
-
|
| 462 |
-
class BasicEmbeddings(Embeddings):
|
| 463 |
-
def embed_documents(self, texts):
|
| 464 |
-
return [self._basic_embed(text) for text in texts]
|
| 465 |
-
|
| 466 |
-
def embed_query(self, text):
|
| 467 |
-
return self._basic_embed(text)
|
| 468 |
-
|
| 469 |
-
def _basic_embed(self, text):
|
| 470 |
-
unique_words = set(text.lower().split())
|
| 471 |
-
embedding = np.zeros(384)
|
| 472 |
-
|
| 473 |
-
for i, word in enumerate(unique_words):
|
| 474 |
-
hash_val = sum(ord(c) for c in word) % 384
|
| 475 |
-
embedding[hash_val] += 1
|
| 476 |
-
|
| 477 |
-
norm = np.linalg.norm(embedding)
|
| 478 |
-
if norm > 0:
|
| 479 |
-
embedding = embedding / norm
|
| 480 |
-
|
| 481 |
-
return embedding.tolist()
|
| 482 |
-
|
| 483 |
-
embeddings = BasicEmbeddings()
|
| 484 |
-
|
| 485 |
-
# Create vectorstore
|
| 486 |
-
vectorstore = Chroma.from_documents(
|
| 487 |
-
splits,
|
| 488 |
-
embedding=embeddings,
|
| 489 |
-
persist_directory="./chroma_db"
|
| 490 |
)
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
except Exception as e:
|
| 495 |
st.error(f"Error processing PDFs: {str(e)}")
|
| 496 |
return None
|
|
@@ -498,13 +357,12 @@ def load_and_index_pdfs():
|
|
| 498 |
retriever = load_and_index_pdfs()
|
| 499 |
|
| 500 |
def check_document_relevance(query, documents, min_similarity=MIN_SIMILARITY_THRESHOLD):
|
| 501 |
-
"""Check
|
| 502 |
if not documents:
|
| 503 |
return [], []
|
| 504 |
|
| 505 |
try:
|
| 506 |
query_embedding = sentence_model.encode(query, convert_to_tensor=True)
|
| 507 |
-
|
| 508 |
relevant_docs = []
|
| 509 |
relevant_scores = []
|
| 510 |
|
|
@@ -515,78 +373,59 @@ def check_document_relevance(query, documents, min_similarity=MIN_SIMILARITY_THR
|
|
| 515 |
if hasattr(util, "pytorch_cos_sim"):
|
| 516 |
similarity = util.pytorch_cos_sim(query_embedding, doc_embedding).item()
|
| 517 |
else:
|
| 518 |
-
# Fallback similarity calculation
|
| 519 |
import torch.nn.functional as F
|
| 520 |
-
import torch
|
| 521 |
-
|
| 522 |
if not isinstance(query_embedding, torch.Tensor):
|
| 523 |
query_embedding = torch.tensor(query_embedding)
|
| 524 |
if not isinstance(doc_embedding, torch.Tensor):
|
| 525 |
doc_embedding = torch.tensor(doc_embedding)
|
| 526 |
-
|
| 527 |
if len(query_embedding.shape) == 1:
|
| 528 |
query_embedding = query_embedding.unsqueeze(0)
|
| 529 |
if len(doc_embedding.shape) == 1:
|
| 530 |
doc_embedding = doc_embedding.unsqueeze(0)
|
| 531 |
-
|
| 532 |
similarity = F.cosine_similarity(query_embedding, doc_embedding).item()
|
| 533 |
|
| 534 |
if similarity > min_similarity:
|
| 535 |
relevant_docs.append(doc)
|
| 536 |
relevant_scores.append(similarity)
|
| 537 |
-
|
| 538 |
except Exception as e:
|
| 539 |
-
print(f"Error calculating similarity: {str(e)}")
|
| 540 |
continue
|
| 541 |
|
| 542 |
-
# Sort by relevance
|
| 543 |
if relevant_docs:
|
| 544 |
sorted_pairs = sorted(zip(relevant_docs, relevant_scores), key=lambda x: x[1], reverse=True)
|
| 545 |
relevant_docs, relevant_scores = zip(*sorted_pairs)
|
| 546 |
return list(relevant_docs), list(relevant_scores)
|
| 547 |
else:
|
| 548 |
return [], []
|
| 549 |
-
|
| 550 |
except Exception as e:
|
| 551 |
-
print(f"Error in relevance check: {str(e)}")
|
| 552 |
return documents, [0.5] * len(documents)
|
| 553 |
|
| 554 |
def clean_message_content(content):
|
| 555 |
-
"""Clean message content
|
| 556 |
if not content:
|
| 557 |
return ""
|
| 558 |
-
|
| 559 |
-
# Remove source citations (but preserve the main content)
|
| 560 |
content = re.sub(r'Source:.*?(?=\n|$)', '', content, flags=re.DOTALL)
|
| 561 |
-
# Remove follow-up questions (but preserve the main content)
|
| 562 |
content = re.sub(r'Follow-up.*?(?=\n|$)', '', content, flags=re.DOTALL)
|
| 563 |
-
# Clean up extra whitespace
|
| 564 |
content = re.sub(r'\n{3,}', '\n\n', content)
|
| 565 |
-
|
| 566 |
return content.strip()
|
| 567 |
|
| 568 |
def needs_pronoun_resolution(query):
|
| 569 |
-
"""
|
| 570 |
query_lower = query.lower()
|
| 571 |
pronouns_to_check = ['they', 'them', 'their', 'it', 'its', 'this', 'that', 'these', 'those']
|
| 572 |
-
|
| 573 |
return any(f' {pronoun} ' in f' {query_lower} ' or
|
| 574 |
query_lower.startswith(f'{pronoun} ') or
|
| 575 |
query_lower.endswith(f' {pronoun}')
|
| 576 |
for pronoun in pronouns_to_check)
|
| 577 |
|
| 578 |
def detect_pronouns_and_resolve(query, conversation_history):
|
| 579 |
-
"""Detect
|
| 580 |
query_lower = query.lower()
|
| 581 |
-
|
| 582 |
-
# Common pronouns that need resolution
|
| 583 |
pronouns = {
|
| 584 |
'they': [], 'them': [], 'their': [], 'theirs': [],
|
| 585 |
'it': [], 'its': [], 'this': [], 'that': [], 'these': [], 'those': [],
|
| 586 |
'he': [], 'him': [], 'his': [], 'she': [], 'her': [], 'hers': []
|
| 587 |
}
|
| 588 |
|
| 589 |
-
# Check if query contains pronouns
|
| 590 |
found_pronouns = []
|
| 591 |
for pronoun in pronouns.keys():
|
| 592 |
if f' {pronoun} ' in f' {query_lower} ' or query_lower.startswith(f'{pronoun} ') or query_lower.endswith(f' {pronoun}'):
|
|
@@ -595,11 +434,9 @@ def detect_pronouns_and_resolve(query, conversation_history):
|
|
| 595 |
if not found_pronouns:
|
| 596 |
return query, False
|
| 597 |
|
| 598 |
-
# Look for potential referents in recent conversation
|
| 599 |
if len(conversation_history) < 2:
|
| 600 |
return query, False
|
| 601 |
|
| 602 |
-
# Get the last user question and assistant response
|
| 603 |
last_user_msg = ""
|
| 604 |
last_assistant_msg = ""
|
| 605 |
|
|
@@ -608,32 +445,26 @@ def detect_pronouns_and_resolve(query, conversation_history):
|
|
| 608 |
last_user_msg = msg["content"]
|
| 609 |
elif msg["role"] == "assistant" and not last_assistant_msg:
|
| 610 |
last_assistant_msg = clean_message_content(msg["content"])
|
| 611 |
-
|
| 612 |
if last_user_msg and last_assistant_msg:
|
| 613 |
break
|
| 614 |
|
| 615 |
-
# Extract key entities/topics from the last question and response
|
| 616 |
potential_referents = []
|
| 617 |
-
|
| 618 |
-
# Common patterns for entities/subjects
|
| 619 |
entity_patterns = [
|
| 620 |
-
r'\b([A-Z][a-z]+ [A-Z][a-z]+)\b',
|
| 621 |
-
r'\b([a-z]+ [a-z]+(?:ies|tion|ment|ness|ity))\b',
|
| 622 |
r'\b(organizations?|institutions?|companies?|governments?|agencies?|groups?)\b',
|
| 623 |
r'\b(students?|teachers?|researchers?|scientists?|experts?|professionals?)\b',
|
| 624 |
r'\b(countries?|nations?|regions?|communities?|populations?)\b'
|
| 625 |
]
|
| 626 |
|
| 627 |
-
# Look for entities in the last user question
|
| 628 |
combined_text = f"{last_user_msg} {last_assistant_msg}"
|
| 629 |
for pattern in entity_patterns:
|
| 630 |
matches = re.findall(pattern, combined_text, re.IGNORECASE)
|
| 631 |
potential_referents.extend(matches)
|
| 632 |
|
| 633 |
-
# Find the most likely referent (prioritize multi-word terms)
|
| 634 |
best_referent = None
|
| 635 |
for ref in potential_referents:
|
| 636 |
-
if len(ref.split()) > 1:
|
| 637 |
best_referent = ref
|
| 638 |
break
|
| 639 |
|
|
@@ -641,10 +472,8 @@ def detect_pronouns_and_resolve(query, conversation_history):
|
|
| 641 |
best_referent = potential_referents[0]
|
| 642 |
|
| 643 |
if best_referent:
|
| 644 |
-
# Create expanded query
|
| 645 |
expanded_query = query
|
| 646 |
for pronoun in found_pronouns:
|
| 647 |
-
# Replace pronoun with referent
|
| 648 |
if pronoun in ['they', 'them', 'their', 'theirs']:
|
| 649 |
if pronoun == 'they':
|
| 650 |
expanded_query = re.sub(rf'\bthey\b', best_referent, expanded_query, flags=re.IGNORECASE)
|
|
@@ -652,75 +481,129 @@ def detect_pronouns_and_resolve(query, conversation_history):
|
|
| 652 |
expanded_query = re.sub(rf'\bthem\b', best_referent, expanded_query, flags=re.IGNORECASE)
|
| 653 |
elif pronoun == 'their':
|
| 654 |
expanded_query = re.sub(rf'\btheir\b', f"{best_referent}'s", expanded_query, flags=re.IGNORECASE)
|
| 655 |
-
|
| 656 |
return expanded_query, True
|
| 657 |
|
| 658 |
return query, False
|
| 659 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 660 |
def handle_topic_questions(prompt):
|
| 661 |
-
"""Handle questions about available topics"""
|
| 662 |
prompt_lower = prompt.lower()
|
| 663 |
-
|
| 664 |
topic_question_patterns = [
|
| 665 |
'what are the other', 'what are the 3 other', 'what are all the topics',
|
| 666 |
'what topics', 'what information do you have', 'what can you help with',
|
| 667 |
'what documents', 'what subjects', 'what areas', 'list topics',
|
| 668 |
'show me the topics', 'what else do you know', 'what other topics'
|
| 669 |
]
|
| 670 |
-
|
| 671 |
is_topic_question = any(pattern in prompt_lower for pattern in topic_question_patterns)
|
| 672 |
-
|
| 673 |
if is_topic_question:
|
| 674 |
topics = get_document_topics()
|
| 675 |
if topics:
|
| 676 |
-
response = f"I have information on these
|
| 677 |
for i, topic in enumerate(topics, 1):
|
| 678 |
response += f"{i}. {topic}\n"
|
| 679 |
response += "\nWhich topic would you like to explore?"
|
| 680 |
return response, True
|
| 681 |
-
|
| 682 |
return None, False
|
| 683 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 684 |
def build_conversation_context():
|
| 685 |
-
"""Build
|
| 686 |
if len(st.session_state.messages) <= 1:
|
| 687 |
return ""
|
| 688 |
-
|
| 689 |
-
# Get recent messages
|
| 690 |
start_idx = 1 if st.session_state.messages[0]["role"] == "assistant" else 0
|
| 691 |
recent_messages = st.session_state.messages[start_idx:-MAX_CONVERSATION_HISTORY-1:-1]
|
| 692 |
recent_messages.reverse()
|
| 693 |
-
|
| 694 |
context_parts = []
|
| 695 |
for msg in recent_messages:
|
| 696 |
role = msg["role"]
|
| 697 |
content = clean_message_content(msg["content"])
|
| 698 |
-
|
| 699 |
if content:
|
| 700 |
if role == "user":
|
| 701 |
context_parts.append(f"User: {content}")
|
| 702 |
elif role == "assistant":
|
| 703 |
context_parts.append(f"Assistant: {content}")
|
| 704 |
-
|
| 705 |
return "\n".join(context_parts)
|
| 706 |
|
| 707 |
def format_text(text):
|
| 708 |
-
"""Basic text formatting
|
| 709 |
replacements = {
|
| 710 |
'alpha': 'α', 'beta': 'β', 'pi': 'π', 'sum': '∑',
|
| 711 |
'leq': '≤', 'geq': '≥', 'neq': '≠', 'approx': '≈'
|
| 712 |
}
|
| 713 |
-
|
| 714 |
for latex, unicode_char in replacements.items():
|
| 715 |
text = text.replace('\\' + latex, unicode_char)
|
| 716 |
-
|
| 717 |
return text
|
| 718 |
|
| 719 |
def is_self_reference_request(query):
|
| 720 |
-
"""Check if
|
| 721 |
query_lower = query.lower().strip()
|
| 722 |
-
|
| 723 |
-
# Direct patterns for self-reference
|
| 724 |
self_reference_patterns = [
|
| 725 |
r'\b(your|that)\s+(answer|response|explanation)\b',
|
| 726 |
r'\bsummariz(e|ing)\s+(that|your|the)\s+(answer|response)\b',
|
|
@@ -729,337 +612,225 @@ def is_self_reference_request(query):
|
|
| 729 |
r'\b(that|your)\s+(previous|last)\s+(answer|response)\b',
|
| 730 |
r'\bwhat\s+you\s+just\s+(said|explained|told)\b'
|
| 731 |
]
|
| 732 |
-
|
| 733 |
-
# Simple self-reference phrases
|
| 734 |
simple_self_ref = [
|
| 735 |
"can you summarize", "can you summarise", "can you sum up",
|
| 736 |
"summarize that", "summarise that", "sum that up",
|
| 737 |
"make it shorter", "shorten it", "brief version",
|
| 738 |
"recap that", "condense that", "in summary"
|
| 739 |
]
|
| 740 |
-
|
| 741 |
-
# Check patterns
|
| 742 |
if any(re.search(pattern, query_lower) for pattern in self_reference_patterns):
|
| 743 |
return True
|
| 744 |
-
|
| 745 |
-
# Check simple phrases
|
| 746 |
if any(phrase in query_lower for phrase in simple_self_ref):
|
| 747 |
return True
|
| 748 |
-
|
| 749 |
-
# Additional check for standalone summarization requests
|
| 750 |
if query_lower in ["summarize", "summarise", "summary", "sum up", "recap", "brief"]:
|
| 751 |
return True
|
| 752 |
-
|
| 753 |
return False
|
| 754 |
|
| 755 |
def is_follow_up_request(query):
|
| 756 |
-
"""Check if
|
| 757 |
if is_self_reference_request(query):
|
| 758 |
return False
|
| 759 |
-
|
| 760 |
query_lower = query.lower()
|
| 761 |
-
|
| 762 |
follow_up_words = [
|
| 763 |
"more", "elaborate", "explain", "clarify", "expand", "further",
|
| 764 |
"continue", "what else", "tell me more", "go on", "details",
|
| 765 |
"can you", "could you", "please", "also", "additionally"
|
| 766 |
]
|
| 767 |
-
|
| 768 |
return any(word in query_lower for word in follow_up_words)
|
| 769 |
|
| 770 |
def clean_model_output(raw_response):
|
| 771 |
-
"""Clean
|
| 772 |
-
|
| 773 |
-
# Remove common system artifacts
|
| 774 |
artifacts = [
|
| 775 |
"You are an educational assistant", "GUIDELINES:", "DOCUMENT CONTENT:",
|
| 776 |
"RECENT CONVERSATION:", "Current question:", "Based on the provided",
|
| 777 |
"According to the document", "STRICT RULES:", "Use ONLY", "Do NOT use",
|
| 778 |
"SAFETY GUIDELINES", "INSTRUCTIONS:"
|
| 779 |
]
|
| 780 |
-
|
| 781 |
for artifact in artifacts:
|
| 782 |
raw_response = raw_response.replace(artifact, "").strip()
|
| 783 |
-
|
| 784 |
-
# Remove unnecessary apologies and general knowledge indicators
|
| 785 |
unwanted_patterns = [
|
| 786 |
r'I apologize if.*?[.!]?\s*',
|
| 787 |
r'I\'m sorry if.*?[.!]?\s*',
|
| 788 |
r'I\'m here to help with.*?[.!]?\s*',
|
| 789 |
]
|
| 790 |
-
|
| 791 |
for pattern in unwanted_patterns:
|
| 792 |
raw_response = re.sub(pattern, '', raw_response, flags=re.IGNORECASE)
|
| 793 |
-
|
| 794 |
-
# Remove lines starting with system indicators
|
| 795 |
lines = raw_response.split("\n")
|
| 796 |
skip_patterns = [
|
| 797 |
"answer this question", "question:", "you are an", "be concise",
|
| 798 |
"i apologize", "i'm sorry"
|
| 799 |
]
|
| 800 |
-
|
| 801 |
cleaned_lines = [
|
| 802 |
line for line in lines
|
| 803 |
if not any(line.lower().strip().startswith(pattern) for pattern in skip_patterns)
|
| 804 |
]
|
| 805 |
-
|
| 806 |
cleaned_text = "\n".join(cleaned_lines)
|
| 807 |
cleaned_text = re.sub(r'\n{3,}', '\n\n', cleaned_text)
|
| 808 |
-
|
| 809 |
return cleaned_text.strip()
|
| 810 |
|
| 811 |
def create_system_message(has_docs, is_self_ref, document_content="", conversation_context="", last_response=""):
|
| 812 |
-
"""Create
|
| 813 |
-
|
| 814 |
base_safety_rules = """
|
| 815 |
-
SAFETY GUIDELINES
|
| 816 |
- Only provide helpful, educational, legal, and appropriate information
|
| 817 |
- Never provide instructions for illegal activities, violence, or harm
|
| 818 |
- Do not generate content that could be used to discriminate or harass
|
| 819 |
- Refuse inappropriate requests politely and suggest educational alternatives
|
| 820 |
-
- If uncertain about content appropriateness, err on the side of caution
|
| 821 |
"""
|
| 822 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
if is_self_ref and last_response:
|
| 824 |
-
return f"""You are
|
| 825 |
|
| 826 |
{base_safety_rules}
|
| 827 |
|
| 828 |
YOUR PREVIOUS RESPONSE:
|
| 829 |
{last_response}
|
| 830 |
|
| 831 |
-
|
| 832 |
{conversation_context}
|
| 833 |
|
| 834 |
INSTRUCTIONS:
|
| 835 |
-
-
|
| 836 |
-
-
|
| 837 |
-
- Provide the requested modification (summary, clarification, etc.) of YOUR previous response
|
| 838 |
-
- Focus ONLY on the content you previously provided
|
| 839 |
-
- Be concise and direct in addressing their request"""
|
| 840 |
-
|
| 841 |
elif has_docs and SAFETY_CONFIG['allow_general_knowledge']:
|
| 842 |
-
return f"""You are
|
| 843 |
|
| 844 |
{base_safety_rules}
|
| 845 |
|
| 846 |
-
|
| 847 |
{conversation_context}
|
| 848 |
|
| 849 |
DOCUMENT CONTENT:
|
| 850 |
{document_content}
|
| 851 |
|
| 852 |
-
|
| 853 |
-
1.
|
| 854 |
-
2. If
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
3. If the answer is NOT in the documents but the question is appropriate and educational:
|
| 859 |
-
- Clearly state: "This specific information isn't in my uploaded documents, but I can provide some educational context:"
|
| 860 |
-
- Then provide helpful, educational information based on general knowledge
|
| 861 |
-
- Keep the response focused and educational
|
| 862 |
-
4. If the question is inappropriate: Politely decline and suggest educational alternatives
|
| 863 |
-
5. Maintain conversational flow and acknowledge previous discussion if relevant
|
| 864 |
-
6. Be direct, educational, and helpful while staying within ethical boundaries"""
|
| 865 |
-
|
| 866 |
elif has_docs:
|
| 867 |
-
return f"""You are
|
| 868 |
|
| 869 |
{base_safety_rules}
|
| 870 |
|
| 871 |
-
|
| 872 |
{conversation_context}
|
| 873 |
|
| 874 |
-
|
| 875 |
{document_content}
|
| 876 |
|
| 877 |
INSTRUCTIONS:
|
| 878 |
-
- Use ONLY the provided
|
| 879 |
-
- If
|
| 880 |
-
-
|
| 881 |
-
- Reference specific details from the documents when possible
|
| 882 |
-
- Be direct and educational while maintaining conversational flow"""
|
| 883 |
-
|
| 884 |
else:
|
| 885 |
-
return f"""You are
|
| 886 |
|
| 887 |
{base_safety_rules}
|
| 888 |
|
| 889 |
-
|
| 890 |
{conversation_context}
|
| 891 |
|
| 892 |
-
The
|
| 893 |
-
|
| 894 |
-
def validate_response_uses_documents(response, document_content):
|
| 895 |
-
"""Check if the response actually uses information from the documents."""
|
| 896 |
-
if not document_content or not response:
|
| 897 |
-
return False
|
| 898 |
-
|
| 899 |
-
# If response explicitly states it's not in documents, that's valid
|
| 900 |
-
not_in_docs_phrases = [
|
| 901 |
-
"not in my uploaded documents", "not available in the provided documents",
|
| 902 |
-
"not covered in my documents", "this specific information isn't in"
|
| 903 |
-
]
|
| 904 |
-
if any(phrase in response.lower() for phrase in not_in_docs_phrases):
|
| 905 |
-
return True # This is a valid response pattern
|
| 906 |
-
|
| 907 |
-
# Check if response contains phrases indicating it can't find info in documents
|
| 908 |
-
decline_phrases = [
|
| 909 |
-
"cannot find", "not in the documents", "not mentioned", "not specified", "not provided"
|
| 910 |
-
]
|
| 911 |
-
if any(phrase in response.lower() for phrase in decline_phrases):
|
| 912 |
-
return False
|
| 913 |
-
|
| 914 |
-
# Check for general knowledge responses (red flags for document-only mode)
|
| 915 |
-
if not SAFETY_CONFIG['allow_general_knowledge']:
|
| 916 |
-
general_knowledge_flags = [
|
| 917 |
-
"generally", "typically", "usually", "commonly", "in general",
|
| 918 |
-
"as a rule", "it is known that", "it is widely accepted",
|
| 919 |
-
"research shows", "studies indicate", "experts believe"
|
| 920 |
-
]
|
| 921 |
-
if any(flag in response.lower() for flag in general_knowledge_flags):
|
| 922 |
-
return False
|
| 923 |
-
|
| 924 |
-
# Simple check: response should have reasonable overlap with document content
|
| 925 |
-
response_words = set(response.lower().split())
|
| 926 |
-
doc_words = set(document_content.lower().split())
|
| 927 |
-
|
| 928 |
-
# Remove common words for better comparison
|
| 929 |
-
common_words = {
|
| 930 |
-
'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by',
|
| 931 |
-
'is', 'are', 'was', 'were', 'a', 'an', 'this', 'that', 'these', 'those',
|
| 932 |
-
'can', 'will', 'would', 'should', 'could', 'may', 'might', 'must'
|
| 933 |
-
}
|
| 934 |
-
response_words -= common_words
|
| 935 |
-
doc_words -= common_words
|
| 936 |
-
|
| 937 |
-
# Check if there's reasonable overlap
|
| 938 |
-
if len(response_words) > 0:
|
| 939 |
-
overlap = len(response_words.intersection(doc_words))
|
| 940 |
-
overlap_ratio = overlap / len(response_words)
|
| 941 |
-
return overlap_ratio >= 0.15
|
| 942 |
-
|
| 943 |
-
return False
|
| 944 |
-
|
| 945 |
-
def classify_query_type(prompt):
|
| 946 |
-
"""Determine how to handle different types of questions."""
|
| 947 |
-
prompt_lower = prompt.lower()
|
| 948 |
-
|
| 949 |
-
# Meta questions about the chatbot itself
|
| 950 |
-
meta_patterns = [
|
| 951 |
-
'what topics', 'what are the other', 'what are the 3 other',
|
| 952 |
-
'what information', 'what can you help', 'what documents',
|
| 953 |
-
'what subjects', 'what areas', 'list topics', 'show me the topics',
|
| 954 |
-
'what else do you know', 'what other topics'
|
| 955 |
-
]
|
| 956 |
-
|
| 957 |
-
if any(pattern in prompt_lower for pattern in meta_patterns):
|
| 958 |
-
return "meta_question"
|
| 959 |
-
|
| 960 |
-
# Summarization requests
|
| 961 |
-
if any(phrase in prompt_lower for phrase in [
|
| 962 |
-
'summarize', 'summarise', 'summary', 'overview'
|
| 963 |
-
]):
|
| 964 |
-
return "summarization"
|
| 965 |
-
|
| 966 |
-
return "factual_question"
|
| 967 |
|
| 968 |
def generate_response_from_model(prompt, relevant_docs=None):
|
| 969 |
-
"""Generate response with
|
| 970 |
if model is None or tokenizer is None:
|
| 971 |
return "Error: Model could not be loaded."
|
| 972 |
|
| 973 |
try:
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
messages
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 1049 |
-
repetition_penalty=1.1,
|
| 1050 |
-
attention_mask=None,
|
| 1051 |
-
use_cache=True
|
| 1052 |
-
)
|
| 1053 |
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
except Exception as e:
|
| 1058 |
-
|
| 1059 |
-
return "I'm sorry, there was an error generating a response."
|
| 1060 |
|
| 1061 |
def is_conversational_input(prompt):
|
| 1062 |
-
"""Check if
|
| 1063 |
conversational_patterns = [
|
| 1064 |
r'^(hi|hello|hey|greetings|howdy)[\s!.?]*$',
|
| 1065 |
r'^(how\s+are\s+you|how\'s\s+it\s+going|what\'s\s+up)[\s!.?]*$',
|
|
@@ -1071,53 +842,12 @@ def is_conversational_input(prompt):
|
|
| 1071 |
r'^(cool|nice|great|awesome|perfect|fine|good)[\s!.?]*$',
|
| 1072 |
r'^(hmm|hm|mhm|uh\s+huh|aha|oh|ooh|wow)[\s!.?]*$'
|
| 1073 |
]
|
| 1074 |
-
|
| 1075 |
prompt_lower = prompt.lower().strip()
|
| 1076 |
return any(re.match(pattern, prompt_lower) for pattern in conversational_patterns)
|
| 1077 |
|
| 1078 |
-
def get_document_topics():
|
| 1079 |
-
"""Extract clean, meaningful topics from loaded documents."""
|
| 1080 |
-
if not PDF_FILES:
|
| 1081 |
-
return []
|
| 1082 |
-
|
| 1083 |
-
topics = []
|
| 1084 |
-
for pdf in PDF_FILES:
|
| 1085 |
-
filename = os.path.basename(pdf).lower()
|
| 1086 |
-
# Remove file extensions
|
| 1087 |
-
clean_name = filename
|
| 1088 |
-
if clean_name.endswith('.pdf'):
|
| 1089 |
-
clean_name = clean_name[:-4]
|
| 1090 |
-
elif clean_name.endswith('.docx'):
|
| 1091 |
-
clean_name = clean_name[:-5]
|
| 1092 |
-
elif clean_name.endswith('.doc'):
|
| 1093 |
-
clean_name = clean_name[:-4]
|
| 1094 |
-
elif clean_name.endswith('.txt'):
|
| 1095 |
-
clean_name = clean_name[:-4]
|
| 1096 |
-
|
| 1097 |
-
# Replace separators with spaces
|
| 1098 |
-
clean_name = re.sub(r'[_-]+', ' ', clean_name)
|
| 1099 |
-
# Remove numbers at the start
|
| 1100 |
-
clean_name = re.sub(r'^\d+\s*', '', clean_name)
|
| 1101 |
-
# Remove common non-meaningful words
|
| 1102 |
-
stop_words = ['document', 'file', 'report', 'briefing', 'overview', 'web', 'pdf']
|
| 1103 |
-
words = [word for word in clean_name.split() if word not in stop_words and len(word) > 2]
|
| 1104 |
-
|
| 1105 |
-
if words:
|
| 1106 |
-
# Take first 4 meaningful words max
|
| 1107 |
-
clean_topic = ' '.join(words[:4])
|
| 1108 |
-
# Capitalize first letter of each word
|
| 1109 |
-
clean_topic = ' '.join(word.capitalize() for word in clean_topic.split())
|
| 1110 |
-
topics.append(clean_topic)
|
| 1111 |
-
|
| 1112 |
-
# Remove duplicates and limit to 5 topics max
|
| 1113 |
-
unique_topics = list(dict.fromkeys(topics))[:5]
|
| 1114 |
-
return unique_topics
|
| 1115 |
-
|
| 1116 |
def generate_conversational_response(prompt):
|
| 1117 |
-
"""Generate
|
| 1118 |
prompt_lower = prompt.lower().strip()
|
| 1119 |
-
|
| 1120 |
-
# Get topic hint for personalization
|
| 1121 |
document_topics = get_document_topics()
|
| 1122 |
topic_hint = ""
|
| 1123 |
if document_topics:
|
|
@@ -1130,109 +860,61 @@ def generate_conversational_response(prompt):
|
|
| 1130 |
|
| 1131 |
conversational_patterns = {
|
| 1132 |
r'^(hi|hello|hey|greetings|howdy)[\s!.?]*$':
|
| 1133 |
-
(f"Hello!
|
| 1134 |
r'^(how\s+are\s+you|how\'s\s+it\s+going|what\'s\s+up)[\s!.?]*$':
|
| 1135 |
-
(f"
|
| 1136 |
r'^(good\s+morning|good\s+afternoon|good\s+evening)[\s!.?]*$':
|
| 1137 |
(f"{prompt.capitalize()}!{topic_hint} What would you like to explore?", True),
|
| 1138 |
r'^(thanks|thank\s+you|thx|ty)[\s!.?]*$':
|
| 1139 |
-
("You're welcome!
|
| 1140 |
r'^(bye|goodbye|see\s+you|farewell)[\s!.?]*$':
|
| 1141 |
-
("Goodbye!
|
| 1142 |
r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$':
|
| 1143 |
-
("
|
| 1144 |
r'^(ok|okay|alright|sure|got\s+it|understood|i\s+see)[\s!.?]*$':
|
| 1145 |
-
("
|
| 1146 |
r'^(yes|yep|yeah)[\s!.?]*$':
|
| 1147 |
-
("What would you like to explore
|
| 1148 |
r'^(no|nope)[\s!.?]*$':
|
| 1149 |
-
("Feel free to ask
|
| 1150 |
r'^(cool|nice|great|awesome|perfect)[\s!.?]*$':
|
| 1151 |
-
("What else
|
| 1152 |
r'^(fine|good)[\s!.?]*$':
|
| 1153 |
-
("What
|
| 1154 |
r'^(hmm|hm|mhm|uh\s+huh|aha|oh|ooh|wow)[\s!.?]*$':
|
| 1155 |
-
("
|
| 1156 |
}
|
| 1157 |
|
| 1158 |
for pattern, (response, continue_flag) in conversational_patterns.items():
|
| 1159 |
if re.match(pattern, prompt_lower):
|
| 1160 |
return response, continue_flag
|
| 1161 |
|
| 1162 |
-
return f"I'm here to help
|
| 1163 |
-
|
| 1164 |
-
def generate_contextual_guidance(prompt):
|
| 1165 |
-
"""Generate contextual guidance based on document topics."""
|
| 1166 |
-
document_topics = get_document_topics()
|
| 1167 |
-
|
| 1168 |
-
if not document_topics:
|
| 1169 |
-
return "What topics from the documents would you like to explore?"
|
| 1170 |
-
|
| 1171 |
-
# Try to match user intent with available topics
|
| 1172 |
-
prompt_lower = prompt.lower()
|
| 1173 |
-
relevant_topics = [
|
| 1174 |
-
topic for topic in document_topics
|
| 1175 |
-
if any(word.lower() in prompt_lower for word in topic.split() if len(word) > 3)
|
| 1176 |
-
]
|
| 1177 |
-
|
| 1178 |
-
if relevant_topics:
|
| 1179 |
-
if len(relevant_topics) == 1:
|
| 1180 |
-
return f"Would you like to explore {relevant_topics[0]}?"
|
| 1181 |
-
else:
|
| 1182 |
-
topic_list = " or ".join(relevant_topics[:2])
|
| 1183 |
-
return f"Would you like to explore {topic_list}?"
|
| 1184 |
-
else:
|
| 1185 |
-
# Show available topics in a clean way
|
| 1186 |
-
if len(document_topics) == 1:
|
| 1187 |
-
return f"I can help with {document_topics[0]}. What would you like to know?"
|
| 1188 |
-
elif len(document_topics) == 2:
|
| 1189 |
-
return f"I can help with {document_topics[0]} or {document_topics[1]}. What interests you?"
|
| 1190 |
-
else:
|
| 1191 |
-
return f"I can help with {document_topics[0]}, {document_topics[1]}, and {len(document_topics)-2} other topic{'s' if len(document_topics)-2 > 1 else ''}. What interests you?"
|
| 1192 |
|
| 1193 |
def generate_follow_up_question(context, conversation_length, prompt=None):
|
| 1194 |
-
"""Generate
|
| 1195 |
-
|
| 1196 |
-
# If user asked for summary, suggest elaboration
|
| 1197 |
-
if prompt and any(word in prompt.lower() for word in ["summary", "summarize", "sum up"]):
|
| 1198 |
-
return "Would you like me to elaborate on any specific part?"
|
| 1199 |
-
|
| 1200 |
-
# Don't generate follow-ups for self-reference requests
|
| 1201 |
if prompt and is_self_reference_request(prompt):
|
| 1202 |
return None
|
| 1203 |
-
|
| 1204 |
-
# Simple context-based questions
|
| 1205 |
context_lower = context.lower()
|
| 1206 |
-
|
| 1207 |
if "process" in context_lower or "step" in context_lower:
|
| 1208 |
-
return "What are the key steps
|
| 1209 |
elif "method" in context_lower or "approach" in context_lower:
|
| 1210 |
-
return "How is this
|
| 1211 |
elif "benefit" in context_lower or "advantage" in context_lower:
|
| 1212 |
-
return "What challenges might arise
|
| 1213 |
-
elif "goal" in context_lower or "target" in context_lower:
|
| 1214 |
-
return "How might these goals be implemented?"
|
| 1215 |
-
|
| 1216 |
-
# Default questions
|
| 1217 |
simple_questions = [
|
| 1218 |
-
"What
|
| 1219 |
"Would you like to explore related concepts?",
|
| 1220 |
-
"
|
| 1221 |
-
"How does this connect to your studies?",
|
| 1222 |
-
"Would you like more details on any part?"
|
| 1223 |
]
|
| 1224 |
-
|
| 1225 |
return simple_questions[conversation_length % len(simple_questions)]
|
| 1226 |
|
| 1227 |
def process_query(prompt, context_docs):
|
| 1228 |
-
"""
|
| 1229 |
-
|
| 1230 |
-
# FIRST: Check question safety - if unsafe, return immediately without document retrieval
|
| 1231 |
is_safe, safety_message = check_question_safety(prompt)
|
| 1232 |
if not is_safe:
|
| 1233 |
return safety_message + generate_educational_alternative(prompt), None, False, None
|
| 1234 |
|
| 1235 |
-
# Handle conversational inputs first
|
| 1236 |
if is_conversational_input(prompt):
|
| 1237 |
response, should_continue = generate_conversational_response(prompt)
|
| 1238 |
reset_pattern = r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$'
|
|
@@ -1240,60 +922,41 @@ def process_query(prompt, context_docs):
|
|
| 1240 |
return response, None, True, None
|
| 1241 |
return response, None, False, None
|
| 1242 |
|
| 1243 |
-
# Classify the query type
|
| 1244 |
query_type = classify_query_type(prompt)
|
| 1245 |
-
|
| 1246 |
-
# Handle meta questions WITHOUT searching documents
|
| 1247 |
if query_type == "meta_question":
|
| 1248 |
response, handled = handle_topic_questions(prompt)
|
| 1249 |
if handled:
|
| 1250 |
return response, None, False, None
|
| 1251 |
|
| 1252 |
-
# Check for self-reference requests
|
| 1253 |
is_self_ref = is_self_reference_request(prompt)
|
| 1254 |
-
|
| 1255 |
if is_self_ref:
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
|
| 1259 |
-
|
| 1260 |
-
return clean_response, None, False, None
|
| 1261 |
|
| 1262 |
-
# Check for pronoun resolution needs
|
| 1263 |
if needs_pronoun_resolution(prompt):
|
| 1264 |
expanded_prompt, was_expanded = detect_pronouns_and_resolve(prompt, st.session_state.messages)
|
| 1265 |
if was_expanded:
|
| 1266 |
prompt = expanded_prompt
|
| 1267 |
-
st.info(f"
|
| 1268 |
|
| 1269 |
-
# Check for follow-up requests
|
| 1270 |
is_followup = is_follow_up_request(prompt)
|
| 1271 |
-
|
| 1272 |
-
# Get relevant documents (only for safe, appropriate questions)
|
| 1273 |
relevant_docs, similarity_scores = check_document_relevance(prompt, context_docs, min_similarity=MIN_SIMILARITY_THRESHOLD)
|
| 1274 |
|
| 1275 |
-
# Generate response
|
| 1276 |
raw_response = generate_response_from_model(prompt, relevant_docs if relevant_docs else None)
|
| 1277 |
-
|
| 1278 |
-
# Clean and format
|
| 1279 |
clean_response = clean_model_output(raw_response)
|
| 1280 |
clean_response = format_text(clean_response)
|
| 1281 |
|
| 1282 |
-
# FIXED: Only add sources if the response actually uses document content AND isn't a safety decline
|
| 1283 |
sources = set()
|
| 1284 |
used_documents = False
|
| 1285 |
-
|
| 1286 |
-
# Don't add sources for safety-declined responses or conversational responses
|
| 1287 |
safety_decline_phrases = [
|
| 1288 |
"keep conversations appropriate", "focused on educational topics",
|
| 1289 |
-
"respectful and focused", "
|
| 1290 |
-
"designed to support ethical learning"
|
| 1291 |
]
|
| 1292 |
-
|
| 1293 |
is_safety_decline = any(phrase in clean_response.lower() for phrase in safety_decline_phrases)
|
| 1294 |
|
| 1295 |
if not is_safety_decline and relevant_docs:
|
| 1296 |
-
# Check if response indicates it used documents
|
| 1297 |
if any(phrase in clean_response.lower() for phrase in [
|
| 1298 |
"according to the document", "the document shows", "based on the provided",
|
| 1299 |
"from the document", "the text states", "as mentioned in"
|
|
@@ -1302,15 +965,11 @@ def process_query(prompt, context_docs):
|
|
| 1302 |
for doc in relevant_docs:
|
| 1303 |
if hasattr(doc, "metadata") and "source" in doc.metadata:
|
| 1304 |
sources.add(doc.metadata["source"])
|
| 1305 |
-
|
| 1306 |
-
# Also check if response explicitly states it's NOT using documents
|
| 1307 |
elif any(phrase in clean_response.lower() for phrase in [
|
| 1308 |
"not in my uploaded documents", "not available in the provided documents",
|
| 1309 |
"not covered in my documents", "this specific information isn't in"
|
| 1310 |
]):
|
| 1311 |
-
used_documents = False
|
| 1312 |
-
|
| 1313 |
-
# For ambiguous cases, check content overlap
|
| 1314 |
else:
|
| 1315 |
document_content = "\n\n".join([doc.page_content for doc in relevant_docs[:3]])
|
| 1316 |
if validate_response_uses_documents(clean_response, document_content):
|
|
@@ -1319,41 +978,49 @@ def process_query(prompt, context_docs):
|
|
| 1319 |
if hasattr(doc, "metadata") and "source" in doc.metadata:
|
| 1320 |
sources.add(doc.metadata["source"])
|
| 1321 |
|
| 1322 |
-
# Add follow-up question (but be selective and not for safety declines)
|
| 1323 |
if not is_followup and not is_safety_decline and len(st.session_state.messages) % 3 == 0:
|
| 1324 |
follow_up = generate_follow_up_question(clean_response, len(st.session_state.messages), prompt)
|
| 1325 |
if follow_up:
|
| 1326 |
-
clean_response += f"\n\
|
| 1327 |
|
| 1328 |
-
# FIXED: Only add sources if documents were actually used AND it's not a safety decline
|
| 1329 |
if used_documents and sources and not is_safety_decline:
|
| 1330 |
clean_response += f"\n\nSource: {', '.join(sorted(sources))}"
|
| 1331 |
|
| 1332 |
return clean_response, ", ".join(sorted(sources)) if sources else None, False, None
|
| 1333 |
|
| 1334 |
-
#
|
| 1335 |
st.title(APP_TITLE)
|
| 1336 |
|
| 1337 |
-
# Sidebar
|
| 1338 |
-
st.sidebar
|
| 1339 |
-
st.
|
| 1340 |
-
|
| 1341 |
-
st.
|
| 1342 |
-
st.
|
| 1343 |
-
|
| 1344 |
-
|
| 1345 |
-
|
| 1346 |
-
|
| 1347 |
-
|
| 1348 |
-
st.
|
| 1349 |
-
|
| 1350 |
-
|
| 1351 |
-
st.
|
| 1352 |
-
|
| 1353 |
-
|
| 1354 |
-
|
| 1355 |
-
|
| 1356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1357 |
|
| 1358 |
# Initialize welcome message
|
| 1359 |
if not st.session_state.messages:
|
|
@@ -1363,81 +1030,58 @@ if not st.session_state.messages:
|
|
| 1363 |
topic_preview = f" I have information about {document_topics[0]}."
|
| 1364 |
elif len(document_topics) == 2:
|
| 1365 |
topic_preview = f" I have information about {document_topics[0]} and {document_topics[1]}."
|
| 1366 |
-
elif len(document_topics) <= 4:
|
| 1367 |
-
topic_list = ", ".join(document_topics[:-1]) + f", and {document_topics[-1]}"
|
| 1368 |
-
topic_preview = f" I have information about {topic_list}."
|
| 1369 |
else:
|
| 1370 |
-
|
|
|
|
| 1371 |
else:
|
| 1372 |
topic_preview = ""
|
| 1373 |
|
| 1374 |
-
welcome_msg = f"Hello! I'm your
|
| 1375 |
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
|
| 1376 |
|
| 1377 |
# Clear conversation button
|
| 1378 |
col1, col2 = st.columns([4, 1])
|
| 1379 |
with col2:
|
| 1380 |
-
if st.button("
|
| 1381 |
st.session_state.conversation_id += 1
|
| 1382 |
st.session_state.messages = []
|
| 1383 |
-
|
| 1384 |
document_topics = get_document_topics()
|
| 1385 |
if document_topics:
|
| 1386 |
-
|
| 1387 |
-
topic_preview = f" I have information about {document_topics[0]}."
|
| 1388 |
-
elif len(document_topics) == 2:
|
| 1389 |
-
topic_preview = f" I have information about {document_topics[0]} and {document_topics[1]}."
|
| 1390 |
-
elif len(document_topics) <= 4:
|
| 1391 |
-
topic_list = ", ".join(document_topics[:-1]) + f", and {document_topics[-1]}"
|
| 1392 |
-
topic_preview = f" I have information about {topic_list}."
|
| 1393 |
-
else:
|
| 1394 |
-
topic_preview = f" I have information about {document_topics[0]}, {document_topics[1]}, and {len(document_topics)-2} other topics."
|
| 1395 |
else:
|
| 1396 |
topic_preview = ""
|
| 1397 |
-
|
| 1398 |
-
welcome_msg = f"Starting a new conversation.{topic_preview} What would you like to learn about today?"
|
| 1399 |
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
|
| 1400 |
st.rerun()
|
| 1401 |
|
| 1402 |
if retriever:
|
| 1403 |
-
# Display
|
| 1404 |
for message in st.session_state.messages:
|
| 1405 |
with st.chat_message(message["role"]):
|
| 1406 |
st.markdown(message["content"])
|
| 1407 |
|
| 1408 |
# User input
|
| 1409 |
-
if prompt := st.chat_input("What would you like to learn
|
| 1410 |
-
# Add user message to history
|
| 1411 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 1412 |
-
|
| 1413 |
with st.chat_message("user"):
|
| 1414 |
st.markdown(prompt)
|
| 1415 |
-
|
| 1416 |
-
# Generate response
|
| 1417 |
with st.chat_message("assistant"):
|
| 1418 |
-
|
| 1419 |
-
|
| 1420 |
-
|
| 1421 |
-
|
| 1422 |
-
|
| 1423 |
-
|
| 1424 |
-
|
| 1425 |
-
if should_reset:
|
| 1426 |
-
st.session_state.conversation_id += 1
|
| 1427 |
-
st.session_state.messages = []
|
| 1428 |
-
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 1429 |
-
st.rerun()
|
| 1430 |
-
|
| 1431 |
-
# Store response in chat history
|
| 1432 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 1433 |
-
|
| 1434 |
-
|
| 1435 |
-
|
| 1436 |
-
|
| 1437 |
-
|
| 1438 |
-
|
| 1439 |
-
|
| 1440 |
-
|
| 1441 |
-
|
| 1442 |
else:
|
| 1443 |
st.error("Failed to load document retrieval system.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import hashlib
|
| 2 |
import numpy as np
|
| 3 |
import os
|
|
|
|
| 18 |
# ====== CONFIGURATION SECTION ======
|
| 19 |
APP_TITLE = "Educational PDF Chatbot"
|
| 20 |
APP_LAYOUT = "wide"
|
| 21 |
+
MODEL_NAME = "Qwen/Qwen2.5-14B-Instruct"
|
|
|
|
|
|
|
| 22 |
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
| 23 |
+
|
| 24 |
CHUNK_SIZE = 2000
|
| 25 |
CHUNK_OVERLAP = 300
|
| 26 |
SEARCH_K = 7
|
| 27 |
MIN_SIMILARITY_THRESHOLD = 0.1
|
|
|
|
|
|
|
| 28 |
MAX_CONVERSATION_HISTORY = 6
|
| 29 |
|
| 30 |
PDF_SEARCH_PATHS = [
|
|
|
|
| 34 |
"pdfs/*.pdf"
|
| 35 |
]
|
| 36 |
|
| 37 |
+
# Response style configurations
|
| 38 |
+
RESPONSE_STYLES = {
|
| 39 |
+
'Balanced': {'temperature': 0.1, 'max_tokens': 500},
|
| 40 |
+
'Concise': {'temperature': 0.05, 'max_tokens': 300},
|
| 41 |
+
'Detailed': {'temperature': 0.2, 'max_tokens': 700}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
SAFETY_CONFIG = {
|
| 45 |
+
'enable_strict_mode': False,
|
| 46 |
+
'educational_alternatives': True,
|
| 47 |
+
'allow_general_knowledge': True
|
| 48 |
}
|
| 49 |
|
|
|
|
|
|
|
| 50 |
CHATBOT_PASSWORD = st.secrets.get("CHATBOT_PASSWORD", os.getenv("CHATBOT_PASSWORD", "edu123"))
|
| 51 |
|
| 52 |
# ====== END CONFIGURATION SECTION ======
|
| 53 |
|
|
|
|
| 54 |
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 55 |
os.environ["HF_HUB_DISABLE_EXPERIMENTAL_WARNING"] = "1"
|
| 56 |
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "0"
|
| 57 |
|
|
|
|
| 58 |
np.float_ = np.float64
|
|
|
|
|
|
|
| 59 |
st.set_page_config(page_title=APP_TITLE, layout=APP_LAYOUT)
|
| 60 |
|
| 61 |
+
# ====== AUTHENTICATION SYSTEM ======
|
| 62 |
def check_password():
|
| 63 |
"""Check password and manage authentication."""
|
|
|
|
|
|
|
| 64 |
if "authenticated" not in st.session_state:
|
| 65 |
st.session_state.authenticated = False
|
|
|
|
| 66 |
if "login_attempts" not in st.session_state:
|
| 67 |
st.session_state.login_attempts = 0
|
| 68 |
|
|
|
|
| 69 |
if st.session_state.authenticated:
|
| 70 |
return True
|
| 71 |
|
|
|
|
| 72 |
st.markdown("""
|
| 73 |
<div style='text-align: center; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 2rem;'>
|
| 74 |
<h1 style='color: white; margin-bottom: 1rem;'>🔒 Educational PDF Chatbot</h1>
|
| 75 |
+
<p style='color: white; font-size: 1.1em;'>Authentication required</p>
|
| 76 |
</div>
|
| 77 |
""", unsafe_allow_html=True)
|
| 78 |
|
|
|
|
| 79 |
if st.session_state.login_attempts >= 5:
|
| 80 |
+
st.error("Too many failed attempts. Please wait a few minutes.")
|
|
|
|
| 81 |
st.stop()
|
| 82 |
|
|
|
|
| 83 |
with st.form("login_form"):
|
| 84 |
+
st.subheader("Enter Password")
|
| 85 |
+
password = st.text_input("Password", type="password", placeholder="Access password")
|
| 86 |
+
submit_button = st.form_submit_button("Access", use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
if submit_button:
|
| 89 |
if password == CHATBOT_PASSWORD:
|
| 90 |
st.session_state.authenticated = True
|
| 91 |
st.session_state.login_attempts = 0
|
|
|
|
| 92 |
st.rerun()
|
| 93 |
else:
|
| 94 |
st.session_state.login_attempts += 1
|
| 95 |
+
remaining = 5 - st.session_state.login_attempts
|
| 96 |
+
if remaining > 0:
|
| 97 |
+
st.error(f"Incorrect password. Attempts remaining: {remaining}")
|
|
|
|
| 98 |
else:
|
| 99 |
+
st.error("Access temporarily blocked.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
return False
|
| 101 |
|
|
|
|
| 102 |
if not check_password():
|
| 103 |
st.stop()
|
| 104 |
|
| 105 |
+
# ====== SESSION STATE INITIALIZATION ======
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
if "messages" not in st.session_state:
|
| 107 |
st.session_state.messages = []
|
|
|
|
| 108 |
if "conversation_id" not in st.session_state:
|
| 109 |
st.session_state.conversation_id = 0
|
|
|
|
| 110 |
if "model_loaded" not in st.session_state:
|
| 111 |
st.session_state.model_loaded = False
|
| 112 |
+
if "response_style" not in st.session_state:
|
| 113 |
+
st.session_state.response_style = "Balanced"
|
| 114 |
|
| 115 |
+
# ====== API CONFIGURATION ======
|
| 116 |
HF_API_KEY = st.secrets.get("HF_TOKEN", os.getenv("HF_TOKEN"))
|
| 117 |
|
| 118 |
if HF_API_KEY:
|
| 119 |
HfFolder.save_token(HF_API_KEY)
|
| 120 |
|
| 121 |
if not HF_API_KEY:
|
| 122 |
+
st.error("Hugging Face API key is missing.")
|
| 123 |
st.stop()
|
| 124 |
|
| 125 |
@st.cache_resource
|
| 126 |
def load_quantized_model():
|
| 127 |
+
"""Load model with 4-bit quantization."""
|
| 128 |
try:
|
|
|
|
| 129 |
quantization_config = BitsAndBytesConfig(
|
| 130 |
load_in_4bit=True,
|
| 131 |
bnb_4bit_compute_dtype=torch.float16,
|
|
|
|
| 155 |
trust_remote_code=True,
|
| 156 |
)
|
| 157 |
|
|
|
|
| 158 |
return model, tokenizer
|
| 159 |
except Exception as e:
|
| 160 |
+
st.error(f"Error loading model: {str(e)}")
|
| 161 |
return None, None
|
| 162 |
|
| 163 |
# Load model
|
| 164 |
if not st.session_state.model_loaded:
|
|
|
|
| 165 |
with st.spinner("Loading model..."):
|
| 166 |
model, tokenizer = load_quantized_model()
|
| 167 |
if model is not None:
|
|
|
|
| 171 |
|
| 172 |
@st.cache_resource
|
| 173 |
def load_sentence_model():
|
| 174 |
+
"""Load sentence transformer model."""
|
| 175 |
try:
|
|
|
|
| 176 |
return SentenceTransformer(EMBEDDING_MODEL, token=HF_API_KEY)
|
| 177 |
except Exception as e:
|
|
|
|
|
|
|
| 178 |
try:
|
| 179 |
return SentenceTransformer("sentence-transformers/all-mpnet-base-v2", token=HF_API_KEY)
|
| 180 |
except Exception as e2:
|
|
|
|
|
|
|
| 181 |
class SimpleEmbedder:
|
| 182 |
def encode(self, texts, convert_to_tensor=True):
|
|
|
|
|
|
|
|
|
|
| 183 |
if isinstance(texts, str):
|
| 184 |
texts = [texts]
|
|
|
|
| 185 |
embeddings = []
|
| 186 |
for text in texts:
|
| 187 |
words = set(text.lower().split())
|
| 188 |
embedding = np.zeros(384)
|
|
|
|
| 189 |
for i, word in enumerate(words):
|
| 190 |
for j, char in enumerate(word):
|
| 191 |
if i < 384:
|
| 192 |
embedding[i] = ord(char) / 255.0
|
|
|
|
| 193 |
embeddings.append(embedding)
|
|
|
|
| 194 |
if convert_to_tensor:
|
| 195 |
return torch.tensor(embeddings)
|
| 196 |
return np.array(embeddings)
|
|
|
|
| 197 |
return SimpleEmbedder()
|
| 198 |
|
| 199 |
sentence_model = load_sentence_model()
|
| 200 |
|
| 201 |
def check_question_safety(question):
|
| 202 |
+
"""Enhanced safety check with improved precision."""
|
|
|
|
|
|
|
|
|
|
| 203 |
question_lower = question.lower().strip()
|
| 204 |
|
|
|
|
| 205 |
profanity_patterns = [
|
| 206 |
r'\bfuck\b', r'\bfucking\b', r'\bfucked\b', r'\bfucker\b',
|
| 207 |
r'\bshit\b', r'\bshitty\b', r'\bshitting\b',
|
| 208 |
r'\bbitch\b', r'\bbitching\b', r'\bbitchy\b',
|
| 209 |
+
r'\bass\b(?!\w)', r'\basshole\b',
|
| 210 |
+
r'\bdamn\b(?!\w)',
|
| 211 |
r'\bcrap\b', r'\bcrappy\b'
|
|
|
|
| 212 |
]
|
| 213 |
|
|
|
|
| 214 |
for pattern in profanity_patterns:
|
| 215 |
if re.search(pattern, question_lower):
|
| 216 |
+
return False, "I'd prefer to keep our conversation respectful and educational."
|
| 217 |
|
|
|
|
| 218 |
unsafe_patterns = [
|
|
|
|
| 219 |
r'\b(kill|murder|hurt|harm|attack|violence|weapon|bomb|suicide)\b',
|
| 220 |
r'\bself[\s\-]harm\b',
|
|
|
|
| 221 |
r'\b(illegal\s+drugs|hack\s+into|steal\s+from|fraud|piracy|money\s+laundering)\b',
|
| 222 |
r'\bhow\s+to\s+(hack|steal|forge|counterfeit)\b',
|
|
|
|
| 223 |
r'\b(personal\s+address|phone\s+number|social\s+security|password|credit\s+card)\b',
|
| 224 |
r'\bprivate\s+information\b',
|
|
|
|
| 225 |
r'\b(hate\s+speech|racist\s+jokes|discrimination\s+against|offensive\s+slur)\b',
|
| 226 |
r'\bextremist\s+(content|views|ideology)\b',
|
|
|
|
| 227 |
r'\b(sexual\s+content|pornographic|explicit\s+content|adult\s+material)\b',
|
| 228 |
+
r'\b(sexy|erotic|intimate|adult\s+humor)\b',
|
| 229 |
r'\b(sexual\s+joke|dirty\s+joke|adult\s+joke)\b'
|
| 230 |
]
|
| 231 |
|
|
|
|
| 232 |
for pattern in unsafe_patterns:
|
| 233 |
if re.search(pattern, question_lower):
|
| 234 |
+
return False, "I keep conversations appropriate and educational."
|
| 235 |
|
|
|
|
| 236 |
educational_inappropriate = [
|
| 237 |
'how to cheat on', 'academic dishonesty', 'plagiarism methods', 'fake certificates',
|
| 238 |
'exam answers for', 'homework answers for', 'cheat codes for', 'bypass security'
|
|
|
|
| 240 |
|
| 241 |
for phrase in educational_inappropriate:
|
| 242 |
if phrase in question_lower:
|
| 243 |
+
return False, "I'm designed to support ethical learning."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
return True, ""
|
| 246 |
|
| 247 |
def generate_educational_alternative(declined_topic):
|
| 248 |
+
"""Provide educational alternatives."""
|
| 249 |
if not SAFETY_CONFIG['educational_alternatives']:
|
| 250 |
return ""
|
| 251 |
|
| 252 |
alternatives = {
|
| 253 |
+
'violence': "I can help with conflict resolution, peace studies, or historical context.",
|
| 254 |
+
'illegal': "I can provide information about legal systems, ethics, or policy studies.",
|
| 255 |
'harm': "I can help with safety education, health information, or wellness topics.",
|
| 256 |
+
'academic_dishonesty': "I can help you understand the topic better or provide study strategies."
|
|
|
|
|
|
|
| 257 |
}
|
| 258 |
|
| 259 |
for key, alternative in alternatives.items():
|
| 260 |
if key in declined_topic.lower():
|
| 261 |
+
return f"\n\n{alternative}"
|
| 262 |
|
| 263 |
+
return "\n\nI'm here to help with educational topics and research questions."
|
| 264 |
|
| 265 |
def clean_document_text(text):
|
| 266 |
+
"""Clean document text."""
|
| 267 |
if not text:
|
| 268 |
return text
|
|
|
|
| 269 |
import unicodedata
|
|
|
|
| 270 |
try:
|
| 271 |
text = unicodedata.normalize('NFKD', text)
|
| 272 |
except:
|
| 273 |
pass
|
|
|
|
|
|
|
| 274 |
text = re.sub(r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]', '', text)
|
|
|
|
|
|
|
| 275 |
text = re.sub(r'[^\x00-\x7F\u00C0-\u00FF]', '', text)
|
|
|
|
|
|
|
| 276 |
text = re.sub(r'\s+', ' ', text)
|
|
|
|
| 277 |
return text.strip()
|
| 278 |
|
| 279 |
def get_pdf_files():
|
| 280 |
+
"""Discover all PDF files."""
|
| 281 |
pdf_files = []
|
|
|
|
| 282 |
for search_path in PDF_SEARCH_PATHS:
|
| 283 |
found_files = glob.glob(search_path)
|
| 284 |
pdf_files.extend(found_files)
|
|
|
|
|
|
|
| 285 |
pdf_files = list(set(pdf_files))
|
| 286 |
pdf_files.sort()
|
| 287 |
return pdf_files
|
|
|
|
| 289 |
PDF_FILES = get_pdf_files()
|
| 290 |
|
| 291 |
if not PDF_FILES:
|
| 292 |
+
st.error("No PDF files found.")
|
|
|
|
|
|
|
|
|
|
| 293 |
st.stop()
|
|
|
|
|
|
|
| 294 |
|
| 295 |
@st.cache_resource
|
| 296 |
def load_and_index_pdfs():
|
| 297 |
+
"""Load and process PDFs."""
|
| 298 |
try:
|
| 299 |
+
documents = []
|
| 300 |
+
for pdf in PDF_FILES:
|
| 301 |
+
if os.path.exists(pdf):
|
| 302 |
+
try:
|
| 303 |
+
loader = PyPDFLoader(pdf)
|
| 304 |
+
docs = loader.load()
|
| 305 |
+
for doc in docs:
|
| 306 |
+
doc.metadata["source"] = pdf
|
| 307 |
+
if "page" in doc.metadata:
|
| 308 |
+
doc.metadata["source"] = f"{os.path.basename(pdf)} (Page {doc.metadata['page']+1})"
|
| 309 |
+
doc.page_content = clean_document_text(doc.page_content)
|
| 310 |
+
documents.extend(docs)
|
| 311 |
+
except Exception as pdf_error:
|
| 312 |
+
continue
|
| 313 |
+
|
| 314 |
+
if not documents:
|
| 315 |
+
return None
|
| 316 |
+
|
| 317 |
+
text_splitter = CharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
|
| 318 |
+
splits = text_splitter.split_documents(documents)
|
| 319 |
+
|
| 320 |
+
try:
|
| 321 |
+
embeddings = HuggingFaceEmbeddings(
|
| 322 |
+
model_name=EMBEDDING_MODEL,
|
| 323 |
+
model_kwargs={"token": HF_API_KEY}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
)
|
| 325 |
+
test_embed = embeddings.embed_query("test")
|
| 326 |
+
if not test_embed or len(test_embed) == 0:
|
| 327 |
+
raise ValueError("Embedding failed")
|
| 328 |
+
except Exception as embed_error:
|
| 329 |
+
from langchain.embeddings.base import Embeddings
|
| 330 |
+
class BasicEmbeddings(Embeddings):
|
| 331 |
+
def embed_documents(self, texts):
|
| 332 |
+
return [self._basic_embed(text) for text in texts]
|
| 333 |
+
def embed_query(self, text):
|
| 334 |
+
return self._basic_embed(text)
|
| 335 |
+
def _basic_embed(self, text):
|
| 336 |
+
unique_words = set(text.lower().split())
|
| 337 |
+
embedding = np.zeros(384)
|
| 338 |
+
for i, word in enumerate(unique_words):
|
| 339 |
+
hash_val = sum(ord(c) for c in word) % 384
|
| 340 |
+
embedding[hash_val] += 1
|
| 341 |
+
norm = np.linalg.norm(embedding)
|
| 342 |
+
if norm > 0:
|
| 343 |
+
embedding = embedding / norm
|
| 344 |
+
return embedding.tolist()
|
| 345 |
+
embeddings = BasicEmbeddings()
|
| 346 |
+
|
| 347 |
+
vectorstore = Chroma.from_documents(
|
| 348 |
+
splits,
|
| 349 |
+
embedding=embeddings,
|
| 350 |
+
persist_directory="./chroma_db"
|
| 351 |
+
)
|
| 352 |
+
return vectorstore.as_retriever(search_kwargs={"k": SEARCH_K})
|
| 353 |
except Exception as e:
|
| 354 |
st.error(f"Error processing PDFs: {str(e)}")
|
| 355 |
return None
|
|
|
|
| 357 |
retriever = load_and_index_pdfs()
|
| 358 |
|
| 359 |
def check_document_relevance(query, documents, min_similarity=MIN_SIMILARITY_THRESHOLD):
|
| 360 |
+
"""Check document relevance using semantic similarity."""
|
| 361 |
if not documents:
|
| 362 |
return [], []
|
| 363 |
|
| 364 |
try:
|
| 365 |
query_embedding = sentence_model.encode(query, convert_to_tensor=True)
|
|
|
|
| 366 |
relevant_docs = []
|
| 367 |
relevant_scores = []
|
| 368 |
|
|
|
|
| 373 |
if hasattr(util, "pytorch_cos_sim"):
|
| 374 |
similarity = util.pytorch_cos_sim(query_embedding, doc_embedding).item()
|
| 375 |
else:
|
|
|
|
| 376 |
import torch.nn.functional as F
|
|
|
|
|
|
|
| 377 |
if not isinstance(query_embedding, torch.Tensor):
|
| 378 |
query_embedding = torch.tensor(query_embedding)
|
| 379 |
if not isinstance(doc_embedding, torch.Tensor):
|
| 380 |
doc_embedding = torch.tensor(doc_embedding)
|
|
|
|
| 381 |
if len(query_embedding.shape) == 1:
|
| 382 |
query_embedding = query_embedding.unsqueeze(0)
|
| 383 |
if len(doc_embedding.shape) == 1:
|
| 384 |
doc_embedding = doc_embedding.unsqueeze(0)
|
|
|
|
| 385 |
similarity = F.cosine_similarity(query_embedding, doc_embedding).item()
|
| 386 |
|
| 387 |
if similarity > min_similarity:
|
| 388 |
relevant_docs.append(doc)
|
| 389 |
relevant_scores.append(similarity)
|
|
|
|
| 390 |
except Exception as e:
|
|
|
|
| 391 |
continue
|
| 392 |
|
|
|
|
| 393 |
if relevant_docs:
|
| 394 |
sorted_pairs = sorted(zip(relevant_docs, relevant_scores), key=lambda x: x[1], reverse=True)
|
| 395 |
relevant_docs, relevant_scores = zip(*sorted_pairs)
|
| 396 |
return list(relevant_docs), list(relevant_scores)
|
| 397 |
else:
|
| 398 |
return [], []
|
|
|
|
| 399 |
except Exception as e:
|
|
|
|
| 400 |
return documents, [0.5] * len(documents)
|
| 401 |
|
| 402 |
def clean_message_content(content):
|
| 403 |
+
"""Clean message content."""
|
| 404 |
if not content:
|
| 405 |
return ""
|
|
|
|
|
|
|
| 406 |
content = re.sub(r'Source:.*?(?=\n|$)', '', content, flags=re.DOTALL)
|
|
|
|
| 407 |
content = re.sub(r'Follow-up.*?(?=\n|$)', '', content, flags=re.DOTALL)
|
|
|
|
| 408 |
content = re.sub(r'\n{3,}', '\n\n', content)
|
|
|
|
| 409 |
return content.strip()
|
| 410 |
|
| 411 |
def needs_pronoun_resolution(query):
|
| 412 |
+
"""Check if query contains pronouns."""
|
| 413 |
query_lower = query.lower()
|
| 414 |
pronouns_to_check = ['they', 'them', 'their', 'it', 'its', 'this', 'that', 'these', 'those']
|
|
|
|
| 415 |
return any(f' {pronoun} ' in f' {query_lower} ' or
|
| 416 |
query_lower.startswith(f'{pronoun} ') or
|
| 417 |
query_lower.endswith(f' {pronoun}')
|
| 418 |
for pronoun in pronouns_to_check)
|
| 419 |
|
| 420 |
def detect_pronouns_and_resolve(query, conversation_history):
|
| 421 |
+
"""Detect and resolve pronouns using context."""
|
| 422 |
query_lower = query.lower()
|
|
|
|
|
|
|
| 423 |
pronouns = {
|
| 424 |
'they': [], 'them': [], 'their': [], 'theirs': [],
|
| 425 |
'it': [], 'its': [], 'this': [], 'that': [], 'these': [], 'those': [],
|
| 426 |
'he': [], 'him': [], 'his': [], 'she': [], 'her': [], 'hers': []
|
| 427 |
}
|
| 428 |
|
|
|
|
| 429 |
found_pronouns = []
|
| 430 |
for pronoun in pronouns.keys():
|
| 431 |
if f' {pronoun} ' in f' {query_lower} ' or query_lower.startswith(f'{pronoun} ') or query_lower.endswith(f' {pronoun}'):
|
|
|
|
| 434 |
if not found_pronouns:
|
| 435 |
return query, False
|
| 436 |
|
|
|
|
| 437 |
if len(conversation_history) < 2:
|
| 438 |
return query, False
|
| 439 |
|
|
|
|
| 440 |
last_user_msg = ""
|
| 441 |
last_assistant_msg = ""
|
| 442 |
|
|
|
|
| 445 |
last_user_msg = msg["content"]
|
| 446 |
elif msg["role"] == "assistant" and not last_assistant_msg:
|
| 447 |
last_assistant_msg = clean_message_content(msg["content"])
|
|
|
|
| 448 |
if last_user_msg and last_assistant_msg:
|
| 449 |
break
|
| 450 |
|
|
|
|
| 451 |
potential_referents = []
|
|
|
|
|
|
|
| 452 |
entity_patterns = [
|
| 453 |
+
r'\b([A-Z][a-z]+ [A-Z][a-z]+)\b',
|
| 454 |
+
r'\b([a-z]+ [a-z]+(?:ies|tion|ment|ness|ity))\b',
|
| 455 |
r'\b(organizations?|institutions?|companies?|governments?|agencies?|groups?)\b',
|
| 456 |
r'\b(students?|teachers?|researchers?|scientists?|experts?|professionals?)\b',
|
| 457 |
r'\b(countries?|nations?|regions?|communities?|populations?)\b'
|
| 458 |
]
|
| 459 |
|
|
|
|
| 460 |
combined_text = f"{last_user_msg} {last_assistant_msg}"
|
| 461 |
for pattern in entity_patterns:
|
| 462 |
matches = re.findall(pattern, combined_text, re.IGNORECASE)
|
| 463 |
potential_referents.extend(matches)
|
| 464 |
|
|
|
|
| 465 |
best_referent = None
|
| 466 |
for ref in potential_referents:
|
| 467 |
+
if len(ref.split()) > 1:
|
| 468 |
best_referent = ref
|
| 469 |
break
|
| 470 |
|
|
|
|
| 472 |
best_referent = potential_referents[0]
|
| 473 |
|
| 474 |
if best_referent:
|
|
|
|
| 475 |
expanded_query = query
|
| 476 |
for pronoun in found_pronouns:
|
|
|
|
| 477 |
if pronoun in ['they', 'them', 'their', 'theirs']:
|
| 478 |
if pronoun == 'they':
|
| 479 |
expanded_query = re.sub(rf'\bthey\b', best_referent, expanded_query, flags=re.IGNORECASE)
|
|
|
|
| 481 |
expanded_query = re.sub(rf'\bthem\b', best_referent, expanded_query, flags=re.IGNORECASE)
|
| 482 |
elif pronoun == 'their':
|
| 483 |
expanded_query = re.sub(rf'\btheir\b', f"{best_referent}'s", expanded_query, flags=re.IGNORECASE)
|
|
|
|
| 484 |
return expanded_query, True
|
| 485 |
|
| 486 |
return query, False
|
| 487 |
|
| 488 |
+
def get_document_topics():
|
| 489 |
+
"""Extract clean topics from documents."""
|
| 490 |
+
if not PDF_FILES:
|
| 491 |
+
return []
|
| 492 |
+
topics = []
|
| 493 |
+
for pdf in PDF_FILES:
|
| 494 |
+
filename = os.path.basename(pdf).lower()
|
| 495 |
+
clean_name = filename
|
| 496 |
+
if clean_name.endswith('.pdf'):
|
| 497 |
+
clean_name = clean_name[:-4]
|
| 498 |
+
clean_name = re.sub(r'[_-]+', ' ', clean_name)
|
| 499 |
+
clean_name = re.sub(r'^\d+\s*', '', clean_name)
|
| 500 |
+
stop_words = ['document', 'file', 'report', 'briefing', 'overview', 'web', 'pdf']
|
| 501 |
+
words = [word for word in clean_name.split() if word not in stop_words and len(word) > 2]
|
| 502 |
+
if words:
|
| 503 |
+
clean_topic = ' '.join(words[:4])
|
| 504 |
+
clean_topic = ' '.join(word.capitalize() for word in clean_topic.split())
|
| 505 |
+
topics.append(clean_topic)
|
| 506 |
+
unique_topics = list(dict.fromkeys(topics))[:5]
|
| 507 |
+
return unique_topics
|
| 508 |
+
|
| 509 |
def handle_topic_questions(prompt):
|
| 510 |
+
"""Handle questions about available topics."""
|
| 511 |
prompt_lower = prompt.lower()
|
|
|
|
| 512 |
topic_question_patterns = [
|
| 513 |
'what are the other', 'what are the 3 other', 'what are all the topics',
|
| 514 |
'what topics', 'what information do you have', 'what can you help with',
|
| 515 |
'what documents', 'what subjects', 'what areas', 'list topics',
|
| 516 |
'show me the topics', 'what else do you know', 'what other topics'
|
| 517 |
]
|
|
|
|
| 518 |
is_topic_question = any(pattern in prompt_lower for pattern in topic_question_patterns)
|
|
|
|
| 519 |
if is_topic_question:
|
| 520 |
topics = get_document_topics()
|
| 521 |
if topics:
|
| 522 |
+
response = f"I have information on these topics:\n\n"
|
| 523 |
for i, topic in enumerate(topics, 1):
|
| 524 |
response += f"{i}. {topic}\n"
|
| 525 |
response += "\nWhich topic would you like to explore?"
|
| 526 |
return response, True
|
|
|
|
| 527 |
return None, False
|
| 528 |
|
| 529 |
+
def classify_query_type(prompt):
|
| 530 |
+
"""Classify query type."""
|
| 531 |
+
prompt_lower = prompt.lower()
|
| 532 |
+
meta_patterns = [
|
| 533 |
+
'what topics', 'what are the other', 'what information',
|
| 534 |
+
'what can you help', 'what documents', 'list topics'
|
| 535 |
+
]
|
| 536 |
+
if any(pattern in prompt_lower for pattern in meta_patterns):
|
| 537 |
+
return "meta_question"
|
| 538 |
+
if any(phrase in prompt_lower for phrase in ['summarize', 'summarise', 'summary', 'overview']):
|
| 539 |
+
return "summarization"
|
| 540 |
+
return "factual_question"
|
| 541 |
+
|
| 542 |
+
def validate_response_uses_documents(response, document_content):
|
| 543 |
+
"""Check if response uses documents."""
|
| 544 |
+
if not document_content or not response:
|
| 545 |
+
return False
|
| 546 |
+
not_in_docs_phrases = [
|
| 547 |
+
"not in my uploaded documents", "not available in the provided documents",
|
| 548 |
+
"not covered in my documents", "this specific information isn't in"
|
| 549 |
+
]
|
| 550 |
+
if any(phrase in response.lower() for phrase in not_in_docs_phrases):
|
| 551 |
+
return True
|
| 552 |
+
decline_phrases = ["cannot find", "not in the documents", "not mentioned"]
|
| 553 |
+
if any(phrase in response.lower() for phrase in decline_phrases):
|
| 554 |
+
return False
|
| 555 |
+
if not SAFETY_CONFIG['allow_general_knowledge']:
|
| 556 |
+
general_knowledge_flags = [
|
| 557 |
+
"generally", "typically", "usually", "commonly", "in general"
|
| 558 |
+
]
|
| 559 |
+
if any(flag in response.lower() for flag in general_knowledge_flags):
|
| 560 |
+
return False
|
| 561 |
+
response_words = set(response.lower().split())
|
| 562 |
+
doc_words = set(document_content.lower().split())
|
| 563 |
+
common_words = {
|
| 564 |
+
'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by',
|
| 565 |
+
'is', 'are', 'was', 'were', 'a', 'an', 'this', 'that', 'these', 'those',
|
| 566 |
+
'can', 'will', 'would', 'should', 'could', 'may', 'might', 'must'
|
| 567 |
+
}
|
| 568 |
+
response_words -= common_words
|
| 569 |
+
doc_words -= common_words
|
| 570 |
+
if len(response_words) > 0:
|
| 571 |
+
overlap = len(response_words.intersection(doc_words))
|
| 572 |
+
overlap_ratio = overlap / len(response_words)
|
| 573 |
+
return overlap_ratio >= 0.15
|
| 574 |
+
return False
|
| 575 |
+
|
| 576 |
def build_conversation_context():
|
| 577 |
+
"""Build conversation context."""
|
| 578 |
if len(st.session_state.messages) <= 1:
|
| 579 |
return ""
|
|
|
|
|
|
|
| 580 |
start_idx = 1 if st.session_state.messages[0]["role"] == "assistant" else 0
|
| 581 |
recent_messages = st.session_state.messages[start_idx:-MAX_CONVERSATION_HISTORY-1:-1]
|
| 582 |
recent_messages.reverse()
|
|
|
|
| 583 |
context_parts = []
|
| 584 |
for msg in recent_messages:
|
| 585 |
role = msg["role"]
|
| 586 |
content = clean_message_content(msg["content"])
|
|
|
|
| 587 |
if content:
|
| 588 |
if role == "user":
|
| 589 |
context_parts.append(f"User: {content}")
|
| 590 |
elif role == "assistant":
|
| 591 |
context_parts.append(f"Assistant: {content}")
|
|
|
|
| 592 |
return "\n".join(context_parts)
|
| 593 |
|
| 594 |
def format_text(text):
|
| 595 |
+
"""Basic text formatting."""
|
| 596 |
replacements = {
|
| 597 |
'alpha': 'α', 'beta': 'β', 'pi': 'π', 'sum': '∑',
|
| 598 |
'leq': '≤', 'geq': '≥', 'neq': '≠', 'approx': '≈'
|
| 599 |
}
|
|
|
|
| 600 |
for latex, unicode_char in replacements.items():
|
| 601 |
text = text.replace('\\' + latex, unicode_char)
|
|
|
|
| 602 |
return text
|
| 603 |
|
| 604 |
def is_self_reference_request(query):
|
| 605 |
+
"""Check if asking about previous response."""
|
| 606 |
query_lower = query.lower().strip()
|
|
|
|
|
|
|
| 607 |
self_reference_patterns = [
|
| 608 |
r'\b(your|that)\s+(answer|response|explanation)\b',
|
| 609 |
r'\bsummariz(e|ing)\s+(that|your|the)\s+(answer|response)\b',
|
|
|
|
| 612 |
r'\b(that|your)\s+(previous|last)\s+(answer|response)\b',
|
| 613 |
r'\bwhat\s+you\s+just\s+(said|explained|told)\b'
|
| 614 |
]
|
|
|
|
|
|
|
| 615 |
simple_self_ref = [
|
| 616 |
"can you summarize", "can you summarise", "can you sum up",
|
| 617 |
"summarize that", "summarise that", "sum that up",
|
| 618 |
"make it shorter", "shorten it", "brief version",
|
| 619 |
"recap that", "condense that", "in summary"
|
| 620 |
]
|
|
|
|
|
|
|
| 621 |
if any(re.search(pattern, query_lower) for pattern in self_reference_patterns):
|
| 622 |
return True
|
|
|
|
|
|
|
| 623 |
if any(phrase in query_lower for phrase in simple_self_ref):
|
| 624 |
return True
|
|
|
|
|
|
|
| 625 |
if query_lower in ["summarize", "summarise", "summary", "sum up", "recap", "brief"]:
|
| 626 |
return True
|
|
|
|
| 627 |
return False
|
| 628 |
|
| 629 |
def is_follow_up_request(query):
|
| 630 |
+
"""Check if asking for more information."""
|
| 631 |
if is_self_reference_request(query):
|
| 632 |
return False
|
|
|
|
| 633 |
query_lower = query.lower()
|
|
|
|
| 634 |
follow_up_words = [
|
| 635 |
"more", "elaborate", "explain", "clarify", "expand", "further",
|
| 636 |
"continue", "what else", "tell me more", "go on", "details",
|
| 637 |
"can you", "could you", "please", "also", "additionally"
|
| 638 |
]
|
|
|
|
| 639 |
return any(word in query_lower for word in follow_up_words)
|
| 640 |
|
| 641 |
def clean_model_output(raw_response):
|
| 642 |
+
"""Clean model output."""
|
|
|
|
|
|
|
| 643 |
artifacts = [
|
| 644 |
"You are an educational assistant", "GUIDELINES:", "DOCUMENT CONTENT:",
|
| 645 |
"RECENT CONVERSATION:", "Current question:", "Based on the provided",
|
| 646 |
"According to the document", "STRICT RULES:", "Use ONLY", "Do NOT use",
|
| 647 |
"SAFETY GUIDELINES", "INSTRUCTIONS:"
|
| 648 |
]
|
|
|
|
| 649 |
for artifact in artifacts:
|
| 650 |
raw_response = raw_response.replace(artifact, "").strip()
|
|
|
|
|
|
|
| 651 |
unwanted_patterns = [
|
| 652 |
r'I apologize if.*?[.!]?\s*',
|
| 653 |
r'I\'m sorry if.*?[.!]?\s*',
|
| 654 |
r'I\'m here to help with.*?[.!]?\s*',
|
| 655 |
]
|
|
|
|
| 656 |
for pattern in unwanted_patterns:
|
| 657 |
raw_response = re.sub(pattern, '', raw_response, flags=re.IGNORECASE)
|
|
|
|
|
|
|
| 658 |
lines = raw_response.split("\n")
|
| 659 |
skip_patterns = [
|
| 660 |
"answer this question", "question:", "you are an", "be concise",
|
| 661 |
"i apologize", "i'm sorry"
|
| 662 |
]
|
|
|
|
| 663 |
cleaned_lines = [
|
| 664 |
line for line in lines
|
| 665 |
if not any(line.lower().strip().startswith(pattern) for pattern in skip_patterns)
|
| 666 |
]
|
|
|
|
| 667 |
cleaned_text = "\n".join(cleaned_lines)
|
| 668 |
cleaned_text = re.sub(r'\n{3,}', '\n\n', cleaned_text)
|
|
|
|
| 669 |
return cleaned_text.strip()
|
| 670 |
|
| 671 |
def create_system_message(has_docs, is_self_ref, document_content="", conversation_context="", last_response=""):
|
| 672 |
+
"""Create system message with style adjustment."""
|
|
|
|
| 673 |
base_safety_rules = """
|
| 674 |
+
SAFETY GUIDELINES:
|
| 675 |
- Only provide helpful, educational, legal, and appropriate information
|
| 676 |
- Never provide instructions for illegal activities, violence, or harm
|
| 677 |
- Do not generate content that could be used to discriminate or harass
|
| 678 |
- Refuse inappropriate requests politely and suggest educational alternatives
|
|
|
|
| 679 |
"""
|
| 680 |
|
| 681 |
+
# Adjust instructions based on response style
|
| 682 |
+
style_instructions = ""
|
| 683 |
+
if st.session_state.response_style == "Concise":
|
| 684 |
+
style_instructions = "\n- Be brief and direct. Provide concise answers without unnecessary details."
|
| 685 |
+
elif st.session_state.response_style == "Detailed":
|
| 686 |
+
style_instructions = "\n- Provide comprehensive, detailed explanations with examples and context."
|
| 687 |
+
else: # Balanced
|
| 688 |
+
style_instructions = "\n- Provide clear, balanced responses with appropriate detail."
|
| 689 |
+
|
| 690 |
if is_self_ref and last_response:
|
| 691 |
+
return f"""You are an educational assistant. The user is asking you to modify your previous response.
|
| 692 |
|
| 693 |
{base_safety_rules}
|
| 694 |
|
| 695 |
YOUR PREVIOUS RESPONSE:
|
| 696 |
{last_response}
|
| 697 |
|
| 698 |
+
CONTEXT:
|
| 699 |
{conversation_context}
|
| 700 |
|
| 701 |
INSTRUCTIONS:
|
| 702 |
+
- Provide the requested modification of your previous response
|
| 703 |
+
- Be concise and direct{style_instructions}"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
elif has_docs and SAFETY_CONFIG['allow_general_knowledge']:
|
| 705 |
+
return f"""You are an educational assistant that provides accurate, safe information.
|
| 706 |
|
| 707 |
{base_safety_rules}
|
| 708 |
|
| 709 |
+
CONTEXT:
|
| 710 |
{conversation_context}
|
| 711 |
|
| 712 |
DOCUMENT CONTENT:
|
| 713 |
{document_content}
|
| 714 |
|
| 715 |
+
STRATEGY:
|
| 716 |
+
1. Check if the question can be answered using the documents
|
| 717 |
+
2. If YES: Provide answer based on document content
|
| 718 |
+
3. If NO but question is educational: State "This information isn't in my documents, but I can provide context:" then give general information
|
| 719 |
+
4. If inappropriate: Politely decline
|
| 720 |
+
5. Be direct, educational, and helpful{style_instructions}"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 721 |
elif has_docs:
|
| 722 |
+
return f"""You are an educational assistant focused on documents.
|
| 723 |
|
| 724 |
{base_safety_rules}
|
| 725 |
|
| 726 |
+
CONTEXT:
|
| 727 |
{conversation_context}
|
| 728 |
|
| 729 |
+
CONTENT:
|
| 730 |
{document_content}
|
| 731 |
|
| 732 |
INSTRUCTIONS:
|
| 733 |
+
- Use ONLY the provided content
|
| 734 |
+
- If not in documents, state this clearly
|
| 735 |
+
- Be direct and educational{style_instructions}"""
|
|
|
|
|
|
|
|
|
|
| 736 |
else:
|
| 737 |
+
return f"""You are an educational assistant.
|
| 738 |
|
| 739 |
{base_safety_rules}
|
| 740 |
|
| 741 |
+
CONTEXT:
|
| 742 |
{conversation_context}
|
| 743 |
|
| 744 |
+
The question doesn't match documents. If educational and appropriate, provide general information while being transparent.{style_instructions}"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 745 |
|
| 746 |
def generate_response_from_model(prompt, relevant_docs=None):
|
| 747 |
+
"""Generate response with safety checks and style control."""
|
| 748 |
if model is None or tokenizer is None:
|
| 749 |
return "Error: Model could not be loaded."
|
| 750 |
|
| 751 |
try:
|
| 752 |
+
is_safe, safety_message = check_question_safety(prompt)
|
| 753 |
+
if not is_safe:
|
| 754 |
+
return safety_message + generate_educational_alternative(prompt)
|
| 755 |
+
|
| 756 |
+
is_self_ref = is_self_reference_request(prompt)
|
| 757 |
+
conversation_context = build_conversation_context()
|
| 758 |
+
|
| 759 |
+
last_assistant_response = ""
|
| 760 |
+
if is_self_ref and len(st.session_state.messages) >= 2:
|
| 761 |
+
for msg in reversed(st.session_state.messages[:-1]):
|
| 762 |
+
if msg["role"] == "assistant":
|
| 763 |
+
last_assistant_response = clean_message_content(msg["content"])
|
| 764 |
+
break
|
| 765 |
+
|
| 766 |
+
document_content = ""
|
| 767 |
+
has_relevant_docs = False
|
| 768 |
+
if relevant_docs:
|
| 769 |
+
doc_texts = []
|
| 770 |
+
for doc in relevant_docs[:3]:
|
| 771 |
+
doc_texts.append(doc.page_content[:800])
|
| 772 |
+
document_content = "\n\n".join(doc_texts)
|
| 773 |
+
has_relevant_docs = len(doc_texts) > 0
|
| 774 |
+
|
| 775 |
+
system_message = create_system_message(
|
| 776 |
+
has_docs=has_relevant_docs,
|
| 777 |
+
is_self_ref=is_self_ref,
|
| 778 |
+
document_content=document_content,
|
| 779 |
+
conversation_context=conversation_context,
|
| 780 |
+
last_response=last_assistant_response
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
user_message = f"Question: {prompt}"
|
| 784 |
+
|
| 785 |
+
try:
|
| 786 |
+
model_device = next(model.parameters()).device
|
| 787 |
+
except:
|
| 788 |
+
model_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 789 |
+
|
| 790 |
+
# Get style parameters
|
| 791 |
+
style_config = RESPONSE_STYLES[st.session_state.response_style]
|
| 792 |
+
temperature = style_config['temperature']
|
| 793 |
+
max_tokens = style_config['max_tokens']
|
| 794 |
+
|
| 795 |
+
if hasattr(tokenizer, "apply_chat_template"):
|
| 796 |
+
messages = [
|
| 797 |
+
{"role": "system", "content": system_message},
|
| 798 |
+
{"role": "user", "content": user_message}
|
| 799 |
+
]
|
| 800 |
+
inputs = tokenizer.apply_chat_template(
|
| 801 |
+
messages,
|
| 802 |
+
return_tensors="pt",
|
| 803 |
+
add_generation_prompt=True,
|
| 804 |
+
tokenize=True,
|
| 805 |
+
padding=False)
|
| 806 |
+
inputs = inputs.to(model.device)
|
| 807 |
+
input_length = inputs.shape[1]
|
| 808 |
+
else:
|
| 809 |
+
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"
|
| 810 |
+
inputs = tokenizer(formatted_prompt, return_tensors="pt", padding=False)
|
| 811 |
+
inputs = inputs["input_ids"].to(model_device)
|
| 812 |
+
input_length = inputs.shape[1]
|
| 813 |
+
|
| 814 |
+
outputs = model.generate(
|
| 815 |
+
inputs,
|
| 816 |
+
max_new_tokens=max_tokens,
|
| 817 |
+
temperature=temperature,
|
| 818 |
+
top_p=0.8,
|
| 819 |
+
do_sample=True,
|
| 820 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 821 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 822 |
+
repetition_penalty=1.1,
|
| 823 |
+
attention_mask=None,
|
| 824 |
+
use_cache=True
|
| 825 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 826 |
|
| 827 |
+
raw_response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
|
| 828 |
+
return raw_response.strip()
|
|
|
|
| 829 |
except Exception as e:
|
| 830 |
+
return "Error generating response."
|
|
|
|
| 831 |
|
| 832 |
def is_conversational_input(prompt):
|
| 833 |
+
"""Check if input is conversational."""
|
| 834 |
conversational_patterns = [
|
| 835 |
r'^(hi|hello|hey|greetings|howdy)[\s!.?]*$',
|
| 836 |
r'^(how\s+are\s+you|how\'s\s+it\s+going|what\'s\s+up)[\s!.?]*$',
|
|
|
|
| 842 |
r'^(cool|nice|great|awesome|perfect|fine|good)[\s!.?]*$',
|
| 843 |
r'^(hmm|hm|mhm|uh\s+huh|aha|oh|ooh|wow)[\s!.?]*$'
|
| 844 |
]
|
|
|
|
| 845 |
prompt_lower = prompt.lower().strip()
|
| 846 |
return any(re.match(pattern, prompt_lower) for pattern in conversational_patterns)
|
| 847 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 848 |
def generate_conversational_response(prompt):
|
| 849 |
+
"""Generate conversational responses."""
|
| 850 |
prompt_lower = prompt.lower().strip()
|
|
|
|
|
|
|
| 851 |
document_topics = get_document_topics()
|
| 852 |
topic_hint = ""
|
| 853 |
if document_topics:
|
|
|
|
| 860 |
|
| 861 |
conversational_patterns = {
|
| 862 |
r'^(hi|hello|hey|greetings|howdy)[\s!.?]*$':
|
| 863 |
+
(f"Hello!{topic_hint} What would you like to learn?", True),
|
| 864 |
r'^(how\s+are\s+you|how\'s\s+it\s+going|what\'s\s+up)[\s!.?]*$':
|
| 865 |
+
(f"Ready to help!{topic_hint} What interests you?", True),
|
| 866 |
r'^(good\s+morning|good\s+afternoon|good\s+evening)[\s!.?]*$':
|
| 867 |
(f"{prompt.capitalize()}!{topic_hint} What would you like to explore?", True),
|
| 868 |
r'^(thanks|thank\s+you|thx|ty)[\s!.?]*$':
|
| 869 |
+
("You're welcome! Anything else?", True),
|
| 870 |
r'^(bye|goodbye|see\s+you|farewell)[\s!.?]*$':
|
| 871 |
+
("Goodbye!", False),
|
| 872 |
r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$':
|
| 873 |
+
("Conversation cleared.", True),
|
| 874 |
r'^(ok|okay|alright|sure|got\s+it|understood|i\s+see)[\s!.?]*$':
|
| 875 |
+
("What else can I help with?", True),
|
| 876 |
r'^(yes|yep|yeah)[\s!.?]*$':
|
| 877 |
+
("What would you like to explore?", True),
|
| 878 |
r'^(no|nope)[\s!.?]*$':
|
| 879 |
+
("Feel free to ask anytime.", True),
|
| 880 |
r'^(cool|nice|great|awesome|perfect)[\s!.?]*$':
|
| 881 |
+
("What else?", True),
|
| 882 |
r'^(fine|good)[\s!.?]*$':
|
| 883 |
+
("What's next?", True),
|
| 884 |
r'^(hmm|hm|mhm|uh\s+huh|aha|oh|ooh|wow)[\s!.?]*$':
|
| 885 |
+
("Something specific you'd like to explore?", True)
|
| 886 |
}
|
| 887 |
|
| 888 |
for pattern, (response, continue_flag) in conversational_patterns.items():
|
| 889 |
if re.match(pattern, prompt_lower):
|
| 890 |
return response, continue_flag
|
| 891 |
|
| 892 |
+
return f"I'm here to help.{topic_hint} What interests you?", True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 893 |
|
| 894 |
def generate_follow_up_question(context, conversation_length, prompt=None):
|
| 895 |
+
"""Generate follow-up question."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 896 |
if prompt and is_self_reference_request(prompt):
|
| 897 |
return None
|
|
|
|
|
|
|
| 898 |
context_lower = context.lower()
|
|
|
|
| 899 |
if "process" in context_lower or "step" in context_lower:
|
| 900 |
+
return "What are the key steps?"
|
| 901 |
elif "method" in context_lower or "approach" in context_lower:
|
| 902 |
+
return "How is this applied in practice?"
|
| 903 |
elif "benefit" in context_lower or "advantage" in context_lower:
|
| 904 |
+
return "What challenges might arise?"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 905 |
simple_questions = [
|
| 906 |
+
"What interests you most?",
|
| 907 |
"Would you like to explore related concepts?",
|
| 908 |
+
"Need more details?"
|
|
|
|
|
|
|
| 909 |
]
|
|
|
|
| 910 |
return simple_questions[conversation_length % len(simple_questions)]
|
| 911 |
|
| 912 |
def process_query(prompt, context_docs):
|
| 913 |
+
"""Process query with enhanced features."""
|
|
|
|
|
|
|
| 914 |
is_safe, safety_message = check_question_safety(prompt)
|
| 915 |
if not is_safe:
|
| 916 |
return safety_message + generate_educational_alternative(prompt), None, False, None
|
| 917 |
|
|
|
|
| 918 |
if is_conversational_input(prompt):
|
| 919 |
response, should_continue = generate_conversational_response(prompt)
|
| 920 |
reset_pattern = r'^(clear|reset|start\s+over|new\s+conversation)[\s!.?]*$'
|
|
|
|
| 922 |
return response, None, True, None
|
| 923 |
return response, None, False, None
|
| 924 |
|
|
|
|
| 925 |
query_type = classify_query_type(prompt)
|
|
|
|
|
|
|
| 926 |
if query_type == "meta_question":
|
| 927 |
response, handled = handle_topic_questions(prompt)
|
| 928 |
if handled:
|
| 929 |
return response, None, False, None
|
| 930 |
|
|
|
|
| 931 |
is_self_ref = is_self_reference_request(prompt)
|
|
|
|
| 932 |
if is_self_ref:
|
| 933 |
+
raw_response = generate_response_from_model(prompt, relevant_docs=None)
|
| 934 |
+
clean_response = clean_model_output(raw_response)
|
| 935 |
+
clean_response = format_text(clean_response)
|
| 936 |
+
return clean_response, None, False, None
|
|
|
|
| 937 |
|
|
|
|
| 938 |
if needs_pronoun_resolution(prompt):
|
| 939 |
expanded_prompt, was_expanded = detect_pronouns_and_resolve(prompt, st.session_state.messages)
|
| 940 |
if was_expanded:
|
| 941 |
prompt = expanded_prompt
|
| 942 |
+
st.info(f"Understood: '{prompt}'")
|
| 943 |
|
|
|
|
| 944 |
is_followup = is_follow_up_request(prompt)
|
|
|
|
|
|
|
| 945 |
relevant_docs, similarity_scores = check_document_relevance(prompt, context_docs, min_similarity=MIN_SIMILARITY_THRESHOLD)
|
| 946 |
|
|
|
|
| 947 |
raw_response = generate_response_from_model(prompt, relevant_docs if relevant_docs else None)
|
|
|
|
|
|
|
| 948 |
clean_response = clean_model_output(raw_response)
|
| 949 |
clean_response = format_text(clean_response)
|
| 950 |
|
|
|
|
| 951 |
sources = set()
|
| 952 |
used_documents = False
|
|
|
|
|
|
|
| 953 |
safety_decline_phrases = [
|
| 954 |
"keep conversations appropriate", "focused on educational topics",
|
| 955 |
+
"respectful and focused", "designed to support ethical learning"
|
|
|
|
| 956 |
]
|
|
|
|
| 957 |
is_safety_decline = any(phrase in clean_response.lower() for phrase in safety_decline_phrases)
|
| 958 |
|
| 959 |
if not is_safety_decline and relevant_docs:
|
|
|
|
| 960 |
if any(phrase in clean_response.lower() for phrase in [
|
| 961 |
"according to the document", "the document shows", "based on the provided",
|
| 962 |
"from the document", "the text states", "as mentioned in"
|
|
|
|
| 965 |
for doc in relevant_docs:
|
| 966 |
if hasattr(doc, "metadata") and "source" in doc.metadata:
|
| 967 |
sources.add(doc.metadata["source"])
|
|
|
|
|
|
|
| 968 |
elif any(phrase in clean_response.lower() for phrase in [
|
| 969 |
"not in my uploaded documents", "not available in the provided documents",
|
| 970 |
"not covered in my documents", "this specific information isn't in"
|
| 971 |
]):
|
| 972 |
+
used_documents = False
|
|
|
|
|
|
|
| 973 |
else:
|
| 974 |
document_content = "\n\n".join([doc.page_content for doc in relevant_docs[:3]])
|
| 975 |
if validate_response_uses_documents(clean_response, document_content):
|
|
|
|
| 978 |
if hasattr(doc, "metadata") and "source" in doc.metadata:
|
| 979 |
sources.add(doc.metadata["source"])
|
| 980 |
|
|
|
|
| 981 |
if not is_followup and not is_safety_decline and len(st.session_state.messages) % 3 == 0:
|
| 982 |
follow_up = generate_follow_up_question(clean_response, len(st.session_state.messages), prompt)
|
| 983 |
if follow_up:
|
| 984 |
+
clean_response += f"\n\n{follow_up}"
|
| 985 |
|
|
|
|
| 986 |
if used_documents and sources and not is_safety_decline:
|
| 987 |
clean_response += f"\n\nSource: {', '.join(sorted(sources))}"
|
| 988 |
|
| 989 |
return clean_response, ", ".join(sorted(sources)) if sources else None, False, None
|
| 990 |
|
| 991 |
+
# ====== STREAMLIT INTERFACE ======
|
| 992 |
st.title(APP_TITLE)
|
| 993 |
|
| 994 |
+
# Sidebar
|
| 995 |
+
with st.sidebar:
|
| 996 |
+
st.title("System")
|
| 997 |
+
|
| 998 |
+
if st.button("Logout", use_container_width=True):
|
| 999 |
+
st.session_state.authenticated = False
|
| 1000 |
+
st.session_state.messages = []
|
| 1001 |
+
st.session_state.conversation_id = 0
|
| 1002 |
+
st.rerun()
|
| 1003 |
+
|
| 1004 |
+
st.markdown("---")
|
| 1005 |
+
st.subheader("Settings")
|
| 1006 |
+
|
| 1007 |
+
# Response style selector
|
| 1008 |
+
response_style = st.selectbox(
|
| 1009 |
+
"Response Style",
|
| 1010 |
+
["Balanced", "Concise", "Detailed"],
|
| 1011 |
+
index=["Balanced", "Concise", "Detailed"].index(st.session_state.response_style),
|
| 1012 |
+
help="Control the length and detail of responses"
|
| 1013 |
+
)
|
| 1014 |
+
|
| 1015 |
+
# Update session state if changed
|
| 1016 |
+
if response_style != st.session_state.response_style:
|
| 1017 |
+
st.session_state.response_style = response_style
|
| 1018 |
+
st.rerun()
|
| 1019 |
+
|
| 1020 |
+
st.markdown("---")
|
| 1021 |
+
st.write("**Documents:**")
|
| 1022 |
+
for pdf in PDF_FILES:
|
| 1023 |
+
st.write(f"• {os.path.basename(pdf)}")
|
| 1024 |
|
| 1025 |
# Initialize welcome message
|
| 1026 |
if not st.session_state.messages:
|
|
|
|
| 1030 |
topic_preview = f" I have information about {document_topics[0]}."
|
| 1031 |
elif len(document_topics) == 2:
|
| 1032 |
topic_preview = f" I have information about {document_topics[0]} and {document_topics[1]}."
|
|
|
|
|
|
|
|
|
|
| 1033 |
else:
|
| 1034 |
+
topic_list = ", ".join(document_topics[:2])
|
| 1035 |
+
topic_preview = f" I have information about {topic_list} and more."
|
| 1036 |
else:
|
| 1037 |
topic_preview = ""
|
| 1038 |
|
| 1039 |
+
welcome_msg = f"Hello! I'm your educational assistant.{topic_preview} What would you like to explore?"
|
| 1040 |
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
|
| 1041 |
|
| 1042 |
# Clear conversation button
|
| 1043 |
col1, col2 = st.columns([4, 1])
|
| 1044 |
with col2:
|
| 1045 |
+
if st.button("New Conversation", use_container_width=True):
|
| 1046 |
st.session_state.conversation_id += 1
|
| 1047 |
st.session_state.messages = []
|
|
|
|
| 1048 |
document_topics = get_document_topics()
|
| 1049 |
if document_topics:
|
| 1050 |
+
topic_preview = f" I have information about {', '.join(document_topics[:2])}."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1051 |
else:
|
| 1052 |
topic_preview = ""
|
| 1053 |
+
welcome_msg = f"Conversation cleared.{topic_preview} What would you like to know?"
|
|
|
|
| 1054 |
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
|
| 1055 |
st.rerun()
|
| 1056 |
|
| 1057 |
if retriever:
|
| 1058 |
+
# Display messages
|
| 1059 |
for message in st.session_state.messages:
|
| 1060 |
with st.chat_message(message["role"]):
|
| 1061 |
st.markdown(message["content"])
|
| 1062 |
|
| 1063 |
# User input
|
| 1064 |
+
if prompt := st.chat_input("What would you like to learn?"):
|
|
|
|
| 1065 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
|
|
|
| 1066 |
with st.chat_message("user"):
|
| 1067 |
st.markdown(prompt)
|
| 1068 |
+
|
|
|
|
| 1069 |
with st.chat_message("assistant"):
|
| 1070 |
+
try:
|
| 1071 |
+
retrieved_docs = retriever.get_relevant_documents(prompt)
|
| 1072 |
+
answer, sources, should_reset, new_follow_up = process_query(prompt, retrieved_docs)
|
| 1073 |
+
|
| 1074 |
+
if should_reset:
|
| 1075 |
+
st.session_state.conversation_id += 1
|
| 1076 |
+
st.session_state.messages = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1077 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 1078 |
+
st.rerun()
|
| 1079 |
+
|
| 1080 |
+
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 1081 |
+
st.markdown(answer)
|
| 1082 |
+
except Exception as e:
|
| 1083 |
+
error_msg = f"Error: {str(e)}"
|
| 1084 |
+
st.error(error_msg)
|
| 1085 |
+
st.session_state.messages.append({"role": "assistant", "content": error_msg})
|
|
|
|
| 1086 |
else:
|
| 1087 |
st.error("Failed to load document retrieval system.")
|