Spaces:
Build error
Build error
File size: 10,637 Bytes
7e8cd1b | 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 | #!/usr/bin/env python3
"""
SIMPLE RAG INGESTION - One Command Does Everything
Auto-loads .env, extracts PDF, cleans text, creates chunks, generates embeddings, updates database.
Usage:
python simple_ingest.py path/to/textbook.pdf "Biology Grade 12"
That's it! No other configuration needed.
"""
import asyncio
import logging
import os
import sys
import uuid
from pathlib import Path
from typing import Optional
# Auto-load .env if available
try:
from dotenv import load_dotenv
env_file = Path(__file__).parent.parent / ".env"
if env_file.exists():
load_dotenv(env_file)
else:
env_file = Path(__file__).parent / ".env"
if env_file.exists():
load_dotenv(env_file)
except ImportError:
pass
# Import services
from app.services.hybrid_extraction import HybridExtractionService, ExtractionConfig
from app.services.text_cleaning import TextCleaningService
from app.services.semantic_chunker import SemanticChunker
from app.services.embedding import EmbeddingService
from app.services.heading_detector import HeadingDetector
from app.config import Config
import psycopg
from psycopg.rows import dict_row
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logger = logging.getLogger(__name__)
class SimpleIngestion:
"""Simple one-command RAG ingestion pipeline"""
def __init__(self):
self.config = Config()
self.extraction_service = HybridExtractionService()
self.text_cleaner = TextCleaningService()
self.chunker = SemanticChunker()
self.heading_detector = HeadingDetector()
self.embedding_service = EmbeddingService(
ollama_url=os.getenv("OLLAMA_URL", "http://localhost:11434")
)
async def ingest_pdf(
self,
pdf_path: str,
title: str,
language: str = "ar",
grade_level: str = "secondary",
document_type: str = "TEXTBOOK",
subject_id: Optional[str] = None,
) -> dict:
"""
Complete PDF ingestion in one function call.
Returns: {
"document_id": "uuid",
"chunks_created": 245,
"quality_score": 0.88,
"status": "success"
}
"""
logger.info("="*60)
logger.info(f" SIMPLE RAG INGESTION")
logger.info("="*60)
logger.info(f"PDF: {pdf_path}")
logger.info(f"Title: {title}")
logger.info(f"Language: {language}")
logger.info(f"Grade: {grade_level}")
logger.info("")
# Step 1: Read PDF
logger.info("π Reading PDF file...")
pdf_path_obj = Path(pdf_path)
if not pdf_path_obj.exists():
raise FileNotFoundError(f"PDF not found: {pdf_path}")
with open(pdf_path_obj, "rb") as f:
pdf_bytes = f.read()
logger.info(f"β
Read {len(pdf_bytes) / (1024*1024):.1f} MB")
# Step 2: Extract with hybrid approach (PyMuPDF + OCR fallback)
logger.info("π₯ Extracting pages (PyMuPDF + OCR fallback)...")
config = ExtractionConfig(
language=language,
dpi=150,
grade_level=grade_level,
use_ocr_only=False
)
pages = await self.extraction_service.extract_pdf_bytes(pdf_bytes, config)
pymupdf_count = sum(1 for _, _, used_ocr in pages if not used_ocr)
ocr_count = sum(1 for _, _, used_ocr in pages if used_ocr)
logger.info(f"β
Extracted {len(pages)} pages")
logger.info(f" PyMuPDF: {pymupdf_count} pages ({100*pymupdf_count/len(pages):.1f}%)")
logger.info(f" OCR: {ocr_count} pages ({100*ocr_count/len(pages):.1f}%)")
# Step 3: Combine and clean text
logger.info("π§Ή Cleaning text...")
full_text = "\n\n".join(text for _, text, _ in pages)
cleaned_text = self.text_cleaner.clean(full_text)
logger.info(f"β
Cleaned: {len(cleaned_text):,} chars ({100*len(cleaned_text)/len(full_text):.1f}% retained)")
# Step 4: Detect sections
logger.info("π Detecting sections...")
headings = self.heading_detector._detect_from_regex(cleaned_text)
unique_sections = len(set(h[1] for h in headings))
logger.info(f"β
Found {unique_sections} sections")
# Step 5: Create semantic chunks
logger.info("βοΈ Creating semantic chunks...")
chunks = self.chunker.chunk_text(cleaned_text)
avg_chunk_size = sum(len(c) for c in chunks) / len(chunks) if chunks else 0
logger.info(f"β
Created {len(chunks)} chunks (avg: {avg_chunk_size:.0f} chars)")
# Step 6: Generate embeddings
logger.info(f"π’ Generating embeddings for {len(chunks)} chunks...")
embeddings = []
failed = 0
for i, chunk in enumerate(chunks):
if (i + 1) % 50 == 0:
logger.info(f" Progress: {i+1}/{len(chunks)}")
try:
embedding = await self.embedding_service.embed(chunk)
embeddings.append(embedding)
except Exception as e:
logger.warning(f"Failed to embed chunk {i}: {e}")
failed += 1
embeddings.append(None)
logger.info(f"β
Embedded {len(embeddings) - failed}/{len(chunks)} chunks")
# Step 7: Save to database
logger.info("πΎ Saving to database...")
database_url = os.getenv("DATABASE_URL")
if not database_url:
raise RuntimeError("DATABASE_URL not set in environment")
doc_id = str(uuid.uuid4())
file_id = str(uuid.uuid4())
async with await psycopg.AsyncConnection.connect(database_url) as conn:
# Create file record
await conn.execute(
"""
INSERT INTO files (
id, original_name, filename, path, mime_type, size,
title, is_public, is_deleted,
target_audience, access_level,
processing_status, processing_attempts, download_count,
created_at, updated_at
) VALUES (
%s, %s, %s, %s, 'application/pdf', %s,
'', false, false,
'ALL', 'PRIVATE',
'COMPLETED', 1, 0,
NOW(), NOW()
)
""",
(file_id, pdf_path_obj.name, pdf_path_obj.name, str(pdf_path), len(pdf_bytes))
)
# Create document record
await conn.execute(
"""
INSERT INTO rag_documents (
id, title, document_type, file_id,
language, status, is_active, chunk_count,
subject_id, grade_level,
created_at, updated_at
) VALUES (
%s, %s, %s, %s,
%s, 'INDEXED', true, %s,
%s, %s,
NOW(), NOW()
)
""",
(doc_id, title, document_type, file_id, language, len(chunks), subject_id, grade_level)
)
# Insert chunks with embeddings
inserted = 0
for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
if embedding is None:
continue
page_num = (i // 5) + 1 # ~5 chunks per page
section = chunk[:100].strip() if chunk else ""
await conn.execute(
"""
INSERT INTO rag_chunks (
id, document_id, chunk_index,
content, embedding,
page_number, section_title,
text_quality_score,
created_at, updated_at
) VALUES (
gen_random_uuid(), %s, %s,
%s, %s,
%s, %s,
%s,
NOW(), NOW()
)
""",
(doc_id, i, chunk, embedding, page_num, section, 0.90)
)
inserted += 1
await conn.commit()
logger.info(f"β
Saved {inserted} chunks to database")
# Calculate quality score
total_chars = len(full_text)
arabic_chars = sum(1 for c in full_text if '\u0600' <= c <= '\u06FF')
arabic_ratio = arabic_chars / total_chars if total_chars > 0 else 0
quality_score = 0.4 * arabic_ratio + 0.3 * (len(cleaned_text) / total_chars) + 0.3 * (inserted / len(chunks))
logger.info("")
logger.info("="*60)
logger.info(" β
INGESTION COMPLETE")
logger.info("="*60)
logger.info(f"Document ID: {doc_id}")
logger.info(f"Chunks: {inserted}/{len(chunks)}")
logger.info(f"Quality Score: {quality_score:.2f}")
logger.info(f"Database: rag_documents + rag_chunks updated")
logger.info("")
return {
"document_id": doc_id,
"file_id": file_id,
"chunks_created": inserted,
"total_chunks": len(chunks),
"quality_score": quality_score,
"extraction_method": {
"pymupdf_pages": pymupdf_count,
"ocr_pages": ocr_count
},
"status": "success"
}
async def main():
"""Main CLI entry point"""
if len(sys.argv) < 3:
print("Usage: python simple_ingest.py <pdf_path> <title> [language] [grade_level]")
print()
print("Examples:")
print(' python simple_ingest.py textbook.pdf "Biology Grade 12"')
print(' python simple_ingest.py textbook.pdf "Math Grade 10" ar secondary')
print()
sys.exit(1)
pdf_path = sys.argv[1]
title = sys.argv[2]
language = sys.argv[3] if len(sys.argv) > 3 else "ar"
grade_level = sys.argv[4] if len(sys.argv) > 4 else "secondary"
ingestion = SimpleIngestion()
try:
result = await ingestion.ingest_pdf(
pdf_path=pdf_path,
title=title,
language=language,
grade_level=grade_level
)
print(f"\nβ
Success! Document ID: {result['document_id']}")
print(f" Chunks: {result['chunks_created']}")
print(f" Quality: {result['quality_score']:.2f}")
sys.exit(0)
except Exception as e:
logger.exception("Ingestion failed")
print(f"\nβ Failed: {e}")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())
|