Spaces:
Sleeping
Sleeping
File size: 10,915 Bytes
f9c215a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | """
ingest.py - PDF Ingestion Pipeline
This script handles the complete ingestion workflow:
1. Read PDF file and extract text by page
2. Clean the extracted text
3. Chunk the text with overlap (500 tokens, 50-100 overlap)
4. Generate embeddings using sentence-transformers
5. Upsert to Pinecone (or save locally with --local-only)
6. Save chunks.jsonl as backup
Usage:
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --index agentic-ai
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --local-only # No Pinecone
Requires:
- PINECONE_API_KEY environment variable (unless using --local-only)
- PDF file at specified path
"""
import os
import sys
import argparse
from typing import List, Dict, Tuple
from tqdm import tqdm
from dotenv import load_dotenv
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Local imports
from app.utils import clean_text, chunk_text, save_chunks_to_jsonl
from app.vectorstore import get_vector_store, PineconeVectorStore, LocalVectorStore
# Load environment variables
load_dotenv()
# Try to import PDF library
try:
import pdfplumber
PDF_LIBRARY = "pdfplumber"
except ImportError:
try:
import PyPDF2
PDF_LIBRARY = "PyPDF2"
except ImportError:
print("ERROR: Neither pdfplumber nor PyPDF2 installed. Please install one.")
sys.exit(1)
# Embedding model
try:
from sentence_transformers import SentenceTransformer
EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
EMBEDDING_DIM = 384
except ImportError:
print("ERROR: sentence-transformers not installed")
sys.exit(1)
def extract_text_from_pdf(pdf_path: str) -> List[Tuple[int, str]]:
"""
Extract text from PDF file, returning text by page.
Args:
pdf_path: Path to the PDF file
Returns:
List of tuples: (page_number, page_text)
"""
print(f"Extracting text from: {pdf_path}")
pages = []
if PDF_LIBRARY == "pdfplumber":
with pdfplumber.open(pdf_path) as pdf:
for i, page in enumerate(pdf.pages):
text = page.extract_text() or ""
pages.append((i + 1, text)) # 1-indexed page numbers
elif PDF_LIBRARY == "PyPDF2":
import PyPDF2
with open(pdf_path, 'rb') as f:
reader = PyPDF2.PdfReader(f)
for i, page in enumerate(reader.pages):
text = page.extract_text() or ""
pages.append((i + 1, text))
print(f"Extracted {len(pages)} pages")
return pages
def load_embedding_model():
"""
Load the sentence-transformers embedding model.
Returns:
SentenceTransformer model instance
"""
print(f"Loading embedding model: {EMBEDDING_MODEL_NAME}")
model = SentenceTransformer(EMBEDDING_MODEL_NAME)
print(f"Model loaded! Embedding dimension: {model.get_sentence_embedding_dimension()}")
return model
def generate_embeddings(
chunks: List[Dict],
model: SentenceTransformer,
batch_size: int = 32
) -> List[Dict]:
"""
Generate embeddings for all chunks.
Args:
chunks: List of chunk dictionaries (must have 'text' key)
model: SentenceTransformer model
batch_size: Batch size for embedding generation
Returns:
Chunks with 'embedding' field added
"""
print(f"Generating embeddings for {len(chunks)} chunks...")
# Extract texts
texts = [chunk['text'] for chunk in chunks]
# Generate embeddings in batches
embeddings = model.encode(
texts,
batch_size=batch_size,
show_progress_bar=True,
convert_to_numpy=True
)
# Add embeddings to chunks
for i, chunk in enumerate(chunks):
chunk['embedding'] = embeddings[i].tolist()
print(f"Generated {len(embeddings)} embeddings")
return chunks
def run_ingestion(
pdf_path: str,
index_name: str = "agentic-ai-ebook",
namespace: str = "agentic-ai",
chunk_size: int = 500,
chunk_overlap: int = 50,
local_only: bool = False,
output_dir: str = "./data"
):
"""
Run the complete ingestion pipeline.
Args:
pdf_path: Path to the PDF file
index_name: Pinecone index name
namespace: Pinecone namespace
chunk_size: Target chunk size in tokens
chunk_overlap: Overlap between chunks in tokens
local_only: If True, skip Pinecone and save locally only
output_dir: Directory for output files
"""
print("=" * 60)
print("RAG Ingestion Pipeline")
print("=" * 60)
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Step 1: Extract text from PDF
print("\n[Step 1/5] Extracting text from PDF...")
pages = extract_text_from_pdf(pdf_path)
if not pages:
print("ERROR: No text extracted from PDF")
return
# Step 2: Clean and chunk text
print("\n[Step 2/5] Cleaning and chunking text...")
all_chunks = []
source_name = os.path.basename(pdf_path)
for page_num, page_text in tqdm(pages, desc="Processing pages"):
# Clean the text
cleaned_text = clean_text(page_text)
if not cleaned_text.strip():
continue
# Chunk the text
page_chunks = chunk_text(
text=cleaned_text,
page_number=page_num,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
source=source_name
)
all_chunks.extend(page_chunks)
print(f"Created {len(all_chunks)} chunks from {len(pages)} pages")
if not all_chunks:
print("ERROR: No chunks created")
return
# Step 3: Load embedding model
print("\n[Step 3/5] Loading embedding model...")
embedding_model = load_embedding_model()
# Step 4: Generate embeddings
print("\n[Step 4/5] Generating embeddings...")
chunks_with_embeddings = generate_embeddings(all_chunks, embedding_model)
# Step 5: Store vectors
print("\n[Step 5/5] Storing vectors...")
if local_only:
# Save to local files only
print("Running in LOCAL-ONLY mode (no Pinecone)")
# Save chunks to JSONL (without embeddings for smaller file)
chunks_file = os.path.join(output_dir, "chunks.jsonl")
save_chunks_to_jsonl(chunks_with_embeddings, chunks_file, include_embeddings=False)
# Save to local vector store
local_store = LocalVectorStore(dimension=EMBEDDING_DIM)
local_store.upsert(chunks_with_embeddings)
# Save vectors to file for later use
vectors_file = os.path.join(output_dir, "vectors.json")
local_store.save_to_file(vectors_file)
print(f"\nLocal files saved to {output_dir}/")
else:
# Upsert to Pinecone
api_key = os.getenv("PINECONE_API_KEY")
if not api_key:
print("ERROR: PINECONE_API_KEY not set. Use --local-only to run without Pinecone.")
# Fall back to local only
print("Falling back to local-only mode...")
chunks_file = os.path.join(output_dir, "chunks.jsonl")
save_chunks_to_jsonl(chunks_with_embeddings, chunks_file, include_embeddings=False)
return
# Initialize Pinecone vector store
vector_store = PineconeVectorStore(
api_key=api_key,
index_name=index_name,
namespace=namespace,
dimension=EMBEDDING_DIM
)
# Create index if needed
if not vector_store.create_index_if_missing():
print("ERROR: Failed to create/connect to Pinecone index")
return
# Upsert vectors
upserted = vector_store.upsert(chunks_with_embeddings)
# Also save chunks locally as backup
chunks_file = os.path.join(output_dir, "chunks.jsonl")
save_chunks_to_jsonl(chunks_with_embeddings, chunks_file, include_embeddings=False)
# Print stats
stats = vector_store.get_index_stats()
print(f"\nPinecone index stats: {stats}")
print("\n" + "=" * 60)
print("Ingestion complete!")
print("=" * 60)
print(f"- Total chunks: {len(chunks_with_embeddings)}")
print(f"- Chunks file: {os.path.join(output_dir, 'chunks.jsonl')}")
if not local_only:
print(f"- Pinecone index: {index_name}")
print(f"- Namespace: {namespace}")
print("=" * 60)
def main():
"""Main entry point with argument parsing."""
parser = argparse.ArgumentParser(
description="Ingest PDF into vector store for RAG",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Ingest to Pinecone (requires PINECONE_API_KEY env var)
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --index agentic-ai
# Local-only mode (no Pinecone needed)
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --local-only
# Custom chunk size
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --chunk-size 400 --overlap 75
"""
)
parser.add_argument(
"--pdf",
type=str,
required=True,
help="Path to the PDF file to ingest"
)
parser.add_argument(
"--index",
type=str,
default="agentic-ai-ebook",
help="Pinecone index name (default: agentic-ai-ebook)"
)
parser.add_argument(
"--namespace",
type=str,
default="agentic-ai",
help="Pinecone namespace (default: agentic-ai)"
)
parser.add_argument(
"--chunk-size",
type=int,
default=500,
help="Target chunk size in tokens (default: 500)"
)
parser.add_argument(
"--overlap",
type=int,
default=50,
help="Chunk overlap in tokens (default: 50)"
)
parser.add_argument(
"--local-only",
action="store_true",
help="Run without Pinecone, save vectors locally"
)
parser.add_argument(
"--output-dir",
type=str,
default="./data",
help="Output directory for local files (default: ./data)"
)
args = parser.parse_args()
# Validate PDF path
if not os.path.exists(args.pdf):
print(f"ERROR: PDF file not found: {args.pdf}")
sys.exit(1)
# Run ingestion
run_ingestion(
pdf_path=args.pdf,
index_name=args.index,
namespace=args.namespace,
chunk_size=args.chunk_size,
chunk_overlap=args.overlap,
local_only=args.local_only,
output_dir=args.output_dir
)
if __name__ == "__main__":
main()
|