Spaces:
Build error
Build error
Download scripts/simple_ingest.py from anwarkxc/trackademi: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/anwarkxc/trackademi/resolve/4e3a10ba7dfd5221b182dfd281fa4cedb91ccb41/scripts/simple_ingest.py
- Command line
-
hf download hf://spaces/anwarkxc/trackademi@4e3a10ba7dfd5221b182dfd281fa4cedb91ccb41/scripts/simple_ingest.py
-
curl -L -o simple_ingest.py https://huggingface.co/spaces/anwarkxc/trackademi/resolve/4e3a10ba7dfd5221b182dfd281fa4cedb91ccb41/scripts/simple_ingest.py
10.6 kB
| #!/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()) | |