LeedsLibraries commited on
Commit
99e5a5a
Β·
verified Β·
1 Parent(s): 1c35e74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -102
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
- """Separate embeddings loading for better caching."""
327
- try:
328
- return HuggingFaceEmbeddings(
329
- model_name=EMBEDDING_MODEL,
330
- model_kwargs={"token": HF_API_KEY, "device": "cuda"} # Use GPU for faster indexing
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
- """Load and process PDFs with batched persistence."""
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
- # Load existing index if available
350
- if os.path.exists(os.path.join(PERSIST_DIR, "chroma.sqlite3")):
351
- print("βœ“ Loading existing vector database")
352
  try:
353
- vectorstore = Chroma(
354
- persist_directory=PERSIST_DIR,
355
- embedding_function=embeddings
356
- )
357
- return vectorstore.as_retriever(search_kwargs={"k": SEARCH_K})
 
 
 
 
358
  except Exception as e:
359
- print(f"⚠️ Error loading existing DB: {e}")
360
- print("Will rebuild index...")
361
-
362
- # Build new index with batching
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
- print("❌ No documents could be loaded")
 
 
381
  return None
382
-
383
- print(f"βœ“ Total pages loaded: {len(documents)}")
384
-
385
- # Split documents
 
386
  text_splitter = CharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
387
  splits = text_splitter.split_documents(documents)
388
- print(f"βœ“ Created {len(splits)} chunks")
389
-
390
- # Create empty vectorstore first
391
- vectorstore = Chroma(
392
- persist_directory=PERSIST_DIR,
393
- embedding_function=embeddings
 
 
 
 
 
394
  )
 
 
 
395
 
396
- # Add documents in batches
397
- BATCH_SIZE = 80 # Adjust based on your PDF count
398
- total_batches = (len(splits) - 1) // BATCH_SIZE + 1
399
-
400
- print(f"πŸ“¦ Processing {total_batches} batches...")
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