Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -321,124 +321,80 @@ if not PDF_FILES:
|
|
| 321 |
st.stop()
|
| 322 |
|
| 323 |
|
|
|
|
| 324 |
@st.cache_resource
|
| 325 |
def get_embeddings():
|
| 326 |
-
"""
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
)
|
| 332 |
-
except:
|
| 333 |
-
return HuggingFaceEmbeddings(
|
| 334 |
-
model_name=EMBEDDING_MODEL,
|
| 335 |
-
model_kwargs={"token": HF_API_KEY}
|
| 336 |
-
)
|
| 337 |
-
|
| 338 |
|
| 339 |
@st.cache_resource
|
| 340 |
def load_and_index_pdfs():
|
| 341 |
-
"""
|
| 342 |
-
import json
|
| 343 |
-
import time
|
| 344 |
-
|
| 345 |
-
PERSIST_DIR = "./chroma_db"
|
| 346 |
-
os.makedirs(PERSIST_DIR, exist_ok=True)
|
| 347 |
embeddings = get_embeddings()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
print("β Loading existing vector database")
|
| 352 |
try:
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
except Exception as e:
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
print("π¦ Building new vector database...")
|
| 364 |
-
documents = []
|
| 365 |
-
for pdf in PDF_FILES:
|
| 366 |
-
if os.path.exists(pdf):
|
| 367 |
-
try:
|
| 368 |
-
loader = PyPDFLoader(pdf)
|
| 369 |
-
docs = loader.load()
|
| 370 |
-
for doc in docs:
|
| 371 |
-
doc.metadata["source"] = f"{os.path.basename(pdf)} (Page {doc.metadata.get('page', 0)+1})"
|
| 372 |
-
doc.page_content = clean_document_text(doc.page_content)
|
| 373 |
-
documents.extend(docs)
|
| 374 |
-
print(f" β Loaded {len(docs)} pages from {os.path.basename(pdf)}")
|
| 375 |
-
except Exception as e:
|
| 376 |
-
print(f" β Error loading {pdf}: {str(e)}")
|
| 377 |
-
continue
|
| 378 |
-
|
| 379 |
if not documents:
|
| 380 |
-
|
|
|
|
|
|
|
| 381 |
return None
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
#
|
|
|
|
| 386 |
text_splitter = CharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
|
| 387 |
splits = text_splitter.split_documents(documents)
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
)
|
|
|
|
|
|
|
|
|
|
| 395 |
|
| 396 |
-
#
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
for i in range(0, len(splits), BATCH_SIZE):
|
| 402 |
-
batch = splits[i:i+BATCH_SIZE]
|
| 403 |
-
batch_num = i // BATCH_SIZE + 1
|
| 404 |
-
|
| 405 |
-
try:
|
| 406 |
-
vectorstore.add_documents(batch)
|
| 407 |
-
vectorstore.persist() # Critical: save after each batch
|
| 408 |
-
print(f" β Batch {batch_num}/{total_batches} processed ({len(batch)} chunks)")
|
| 409 |
-
|
| 410 |
-
# Small pause to avoid resource spikes
|
| 411 |
-
time.sleep(0.05)
|
| 412 |
-
except Exception as e:
|
| 413 |
-
print(f" β Error in batch {batch_num}: {str(e)}")
|
| 414 |
-
continue
|
| 415 |
-
|
| 416 |
-
print("β Vector database created and persisted")
|
| 417 |
-
|
| 418 |
-
# Save signature to avoid unnecessary rebuilds
|
| 419 |
-
try:
|
| 420 |
-
sig_file = os.path.join(PERSIST_DIR, "meta.json")
|
| 421 |
-
pdf_sig = hashlib.sha256()
|
| 422 |
-
for pdf in sorted(PDF_FILES):
|
| 423 |
-
if os.path.exists(pdf):
|
| 424 |
-
stat = os.stat(pdf)
|
| 425 |
-
pdf_sig.update(pdf.encode())
|
| 426 |
-
pdf_sig.update(str(stat.st_mtime).encode())
|
| 427 |
-
pdf_sig.update(str(stat.st_size).encode())
|
| 428 |
-
|
| 429 |
-
with open(sig_file, 'w') as f:
|
| 430 |
-
json.dump({
|
| 431 |
-
'signature': pdf_sig.hexdigest(),
|
| 432 |
-
'created_at': datetime.now().isoformat(),
|
| 433 |
-
'num_documents': len(documents),
|
| 434 |
-
'num_chunks': len(splits)
|
| 435 |
-
}, f)
|
| 436 |
-
print("β Signature saved")
|
| 437 |
-
except Exception as e:
|
| 438 |
-
print(f"β οΈ Could not save signature: {e}")
|
| 439 |
-
|
| 440 |
-
return vectorstore.as_retriever(search_kwargs={"k": SEARCH_K})
|
| 441 |
|
|
|
|
| 442 |
|
| 443 |
|
| 444 |
# β ADDED: Lazy loading helper function
|
|
|
|
| 321 |
st.stop()
|
| 322 |
|
| 323 |
|
| 324 |
+
@st.cache_resource
|
| 325 |
@st.cache_resource
|
| 326 |
def get_embeddings():
|
| 327 |
+
"""Load embeddings on CPU to avoid GPU contention."""
|
| 328 |
+
return HuggingFaceEmbeddings(
|
| 329 |
+
model_name=EMBEDDING_MODEL,
|
| 330 |
+
model_kwargs={"token": HF_API_KEY} # CPU only - no device="cuda"
|
| 331 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
@st.cache_resource
|
| 334 |
def load_and_index_pdfs():
|
| 335 |
+
"""Fast in-memory index. Rebuilds on cold start, no disk persistence."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
embeddings = get_embeddings()
|
| 337 |
+
|
| 338 |
+
status = st.empty()
|
| 339 |
+
progress = st.progress(0)
|
| 340 |
+
|
| 341 |
+
# 1) Load PDFs
|
| 342 |
+
status.write("π Loading PDFs...")
|
| 343 |
+
documents = []
|
| 344 |
+
total_pdfs = len(PDF_FILES)
|
| 345 |
|
| 346 |
+
for idx, pdf in enumerate(PDF_FILES, start=1):
|
| 347 |
+
status.write(f"π Loading {os.path.basename(pdf)} ({idx}/{total_pdfs})...")
|
|
|
|
| 348 |
try:
|
| 349 |
+
loader = PyPDFLoader(pdf)
|
| 350 |
+
docs = loader.load()
|
| 351 |
+
|
| 352 |
+
for doc in docs:
|
| 353 |
+
doc.metadata["source"] = f"{os.path.basename(pdf)} (Page {doc.metadata.get('page', 0)+1})"
|
| 354 |
+
doc.page_content = clean_document_text(doc.page_content)
|
| 355 |
+
|
| 356 |
+
documents.extend(docs)
|
| 357 |
+
status.write(f" β
Loaded {len(docs)} pages from {os.path.basename(pdf)}")
|
| 358 |
except Exception as e:
|
| 359 |
+
status.write(f"β οΈ Skipping {os.path.basename(pdf)}: {e}")
|
| 360 |
+
|
| 361 |
+
progress.progress(int(30 * idx / total_pdfs))
|
| 362 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
if not documents:
|
| 364 |
+
status.write("β No documents loaded.")
|
| 365 |
+
progress.empty()
|
| 366 |
+
status.empty()
|
| 367 |
return None
|
| 368 |
+
|
| 369 |
+
status.write(f"β
Loaded {len(documents)} total pages")
|
| 370 |
+
|
| 371 |
+
# 2) Split
|
| 372 |
+
status.write("βοΈ Splitting into chunks...")
|
| 373 |
text_splitter = CharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
|
| 374 |
splits = text_splitter.split_documents(documents)
|
| 375 |
+
status.write(f"β
Created {len(splits)} chunks")
|
| 376 |
+
|
| 377 |
+
progress.progress(50)
|
| 378 |
+
|
| 379 |
+
# 3) Build vectorstore (in-memory - NO disk persistence)
|
| 380 |
+
status.write("π’ Building vector database...")
|
| 381 |
+
vectorstore = Chroma.from_documents(
|
| 382 |
+
splits,
|
| 383 |
+
embedding=embeddings,
|
| 384 |
+
collection_name="educational_kb"
|
| 385 |
+
# NOTE: No persist_directory = stays in memory
|
| 386 |
)
|
| 387 |
+
|
| 388 |
+
progress.progress(100)
|
| 389 |
+
status.write("β
Knowledge base ready!")
|
| 390 |
|
| 391 |
+
# Clear UI elements after 2 seconds
|
| 392 |
+
import time
|
| 393 |
+
time.sleep(2)
|
| 394 |
+
progress.empty()
|
| 395 |
+
status.empty()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
+
return vectorstore.as_retriever(search_kwargs={"k": SEARCH_K})
|
| 398 |
|
| 399 |
|
| 400 |
# β ADDED: Lazy loading helper function
|