Zubaish commited on
Commit
73b7c2a
·
1 Parent(s): 0b4a5ba
Files changed (1) hide show
  1. ingest.py +24 -36
ingest.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  from datasets import load_dataset
3
  from langchain_community.document_loaders import PyPDFLoader
4
  from langchain_text_splitters import RecursiveCharacterTextSplitter
@@ -7,70 +8,57 @@ from langchain_chroma import Chroma
7
  from config import KB_DIR, HF_DATASET_REPO, EMBEDDING_MODEL, CHROMA_DIR
8
 
9
  def run_ingestion():
 
 
 
10
  os.makedirs(KB_DIR, exist_ok=True)
11
 
12
- print(f"⬇️ Loading dataset from {HF_DATASET_REPO}...")
13
 
14
- # Remove 'decode=False' to avoid the ValueError
15
- # We load the dataset normally; for PDF folders, it usually provides paths to the files
16
- dataset = load_dataset(HF_DATASET_REPO, split="train")
17
 
18
- print(f"📊 Dataset columns: {dataset.column_names}")
19
-
20
  pdf_paths = []
21
  for i, row in enumerate(dataset):
22
- # In a PdfFolder dataset, the 'pdf' column often contains a dict
23
- # with 'path' and 'bytes' or it might be a direct path string.
24
  pdf_data = row.get("pdf")
25
-
26
- # Try to get the original filename from the metadata if it exists
27
- fname = row.get("file_name") or row.get("filename") or f"doc_{i}.pdf"
28
- path = os.path.join(KB_DIR, fname)
29
-
30
- if pdf_data is None:
31
  continue
32
 
33
- with open(path, "wb") as f:
34
- # Check if it's the dictionary format {'path': ..., 'bytes': ...}
35
- if isinstance(pdf_data, dict) and "bytes" in pdf_data:
36
- f.write(pdf_data["bytes"])
37
- # Check if it's already a bytes object
38
- elif isinstance(pdf_data, bytes):
39
- f.write(pdf_data)
40
- else:
41
- # Fallback: If it's the decoded 'PDF' object that caused the
42
- # previous error, we try to access the underlying bytes
43
- try:
44
- f.write(pdf_data.read())
45
- except:
46
- print(f"⚠️ Could not write file {fname} - unexpected format: {type(pdf_data)}")
47
- continue
48
 
 
 
 
 
 
49
  pdf_paths.append(path)
50
 
51
- print(f"📄 Processing {len(pdf_paths)} documents...")
52
  docs = []
53
  for p in pdf_paths:
54
  try:
55
  loader = PyPDFLoader(p)
56
  docs.extend(loader.load())
57
  except Exception as e:
58
- print(f"❌ Error parsing PDF {p}: {e}")
 
 
 
59
 
60
- # Split text for the vector database
61
- splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
62
  splits = splitter.split_documents(docs)
63
 
64
- print("🧠 Initializing Vector DB...")
65
  embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
66
 
67
- # This creates the persistent database on disk
68
  Chroma.from_documents(
69
  documents=splits,
70
  embedding=embeddings,
71
  persist_directory=CHROMA_DIR
72
  )
73
- print(f"✅ Ingestion complete. Data saved to {CHROMA_DIR}")
74
 
75
  if __name__ == "__main__":
76
  run_ingestion()
 
1
  import os
2
+ import shutil
3
  from datasets import load_dataset
4
  from langchain_community.document_loaders import PyPDFLoader
5
  from langchain_text_splitters import RecursiveCharacterTextSplitter
 
8
  from config import KB_DIR, HF_DATASET_REPO, EMBEDDING_MODEL, CHROMA_DIR
9
 
10
  def run_ingestion():
11
+ # Clean setup
12
+ if os.path.exists(KB_DIR): shutil.rmtree(KB_DIR)
13
+ if os.path.exists(CHROMA_DIR): shutil.rmtree(CHROMA_DIR)
14
  os.makedirs(KB_DIR, exist_ok=True)
15
 
16
+ print(f"⬇️ Loading raw dataset from {HF_DATASET_REPO}...")
17
 
18
+ # Crucial: load as binary to get raw bytes instead of 'PDF' objects
19
+ dataset = load_dataset(HF_DATASET_REPO, split="train").with_format("binary")
 
20
 
 
 
21
  pdf_paths = []
22
  for i, row in enumerate(dataset):
23
+ # Your dataset column is named 'pdf'
 
24
  pdf_data = row.get("pdf")
25
+ if not pdf_data:
 
 
 
 
 
26
  continue
27
 
28
+ # Extract bytes from the HF feature dictionary
29
+ raw_bytes = pdf_data.get("bytes") if isinstance(pdf_data, dict) else pdf_data
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ fname = f"doc_{i}.pdf"
32
+ path = os.path.join(KB_DIR, fname)
33
+
34
+ with open(path, "wb") as f:
35
+ f.write(raw_bytes)
36
  pdf_paths.append(path)
37
 
38
+ print(f"📄 Loading and splitting {len(pdf_paths)} documents...")
39
  docs = []
40
  for p in pdf_paths:
41
  try:
42
  loader = PyPDFLoader(p)
43
  docs.extend(loader.load())
44
  except Exception as e:
45
+ print(f"⚠️ Error reading {p}: {e}")
46
+
47
+ if not docs:
48
+ raise ValueError("❌ No documents were successfully loaded. Check your dataset!")
49
 
50
+ splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
 
51
  splits = splitter.split_documents(docs)
52
 
53
+ print(f"🧠 Indexing {len(splits)} chunks into ChromaDB...")
54
  embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
55
 
 
56
  Chroma.from_documents(
57
  documents=splits,
58
  embedding=embeddings,
59
  persist_directory=CHROMA_DIR
60
  )
61
+ print(f"✅ Ingestion complete. DB saved to {CHROMA_DIR}")
62
 
63
  if __name__ == "__main__":
64
  run_ingestion()