Spaces:
Build error
Build error
Download scripts/ingest_pdf.py from anwarkxc/trackademi: direct link, hf CLI and curl.
- Browser
- Download file 5.01 kB
-
https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/scripts/ingest_pdf.py
- Command line
-
hf download hf://spaces/anwarkxc/trackademi/scripts/ingest_pdf.py
-
curl -L -o ingest_pdf.py https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/scripts/ingest_pdf.py
5.01 kB
| """Standalone script to ingest a PDF into the RAG pipeline with OCR support. | |
| Usage: | |
| python scripts/ingest_pdf.py <pdf_path> --title "Document Title" [--grade PRIMARY_6] [--doc-type TEXTBOOK] | |
| This runs outside of the HTTP server, avoiding request timeouts for large PDFs. | |
| """ | |
| import asyncio | |
| import argparse | |
| import logging | |
| import sys | |
| import os | |
| import uuid | |
| # Limit torch parallelism to reduce memory usage | |
| os.environ.setdefault("OMP_NUM_THREADS", "1") | |
| os.environ.setdefault("MKL_NUM_THREADS", "1") | |
| # Add project root to path | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from sqlalchemy import text as sql_text | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s", | |
| ) | |
| logger = logging.getLogger("ingest_pdf") | |
| async def main(): | |
| parser = argparse.ArgumentParser(description="Ingest a PDF into the RAG pipeline") | |
| parser.add_argument("pdf_path", help="Path to the PDF file") | |
| parser.add_argument("--title", required=True, help="Document title") | |
| parser.add_argument("--doc-type", default="TEXTBOOK", | |
| help="Document type (TEXTBOOK, TEACHERS_GUIDE, etc.)") | |
| parser.add_argument("--grade", default=None, | |
| help="Grade level (e.g. PRIMARY_6)") | |
| parser.add_argument("--subject-id", default=None, | |
| help="Subject UUID (optional)") | |
| args = parser.parse_args() | |
| pdf_path = args.pdf_path | |
| if not os.path.exists(pdf_path): | |
| logger.error("File not found: %s", pdf_path) | |
| sys.exit(1) | |
| with open(pdf_path, "rb") as f: | |
| pdf_bytes = f.read() | |
| logger.info("Read %d bytes from %s", len(pdf_bytes), pdf_path) | |
| # Initialize database and services | |
| from app.config import get_settings | |
| from app.database import init_db, close_db | |
| from app.services.embed import EmbedService | |
| from app.services.ingest import IngestService | |
| settings = get_settings() | |
| await init_db() | |
| embed_service = EmbedService() | |
| ingest_service = IngestService(embed_service) | |
| # Create DB session | |
| from app.database import get_rag_engine | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.orm import sessionmaker | |
| engine = get_rag_engine() | |
| async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) | |
| import httpx | |
| async with async_session() as session, httpx.AsyncClient( | |
| timeout=httpx.Timeout(connect=10.0, read=120.0, write=30.0, pool=10.0) | |
| ) as client: | |
| doc_id = str(uuid.uuid4()) | |
| file_id = str(uuid.uuid4()) | |
| original_name = os.path.basename(pdf_path) | |
| # Insert files row | |
| await session.execute( | |
| sql_text(""" | |
| 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 ( | |
| :id, :original_name, :filename, :path, 'application/pdf', :size, | |
| '', false, false, | |
| 'ALL', 'PRIVATE', | |
| 'PENDING', 0, 0, | |
| NOW(), NOW() | |
| ) | |
| """), | |
| { | |
| "id": file_id, | |
| "original_name": original_name, | |
| "filename": original_name, | |
| "path": original_name, | |
| "size": len(pdf_bytes), | |
| }, | |
| ) | |
| # Insert rag_documents row | |
| await session.execute( | |
| sql_text(""" | |
| 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 ( | |
| :id, :title, :doc_type, :file_id, | |
| :language, 'PENDING', true, 0, | |
| :subject_id, :grade_level, | |
| NOW(), NOW() | |
| ) | |
| """), | |
| { | |
| "id": doc_id, | |
| "title": args.title, | |
| "doc_type": args.doc_type, | |
| "file_id": file_id, | |
| "language": settings.DEFAULT_DOCUMENT_LANGUAGE, | |
| "subject_id": args.subject_id, | |
| "grade_level": args.grade, | |
| }, | |
| ) | |
| await session.commit() | |
| logger.info("Created rag_documents row %s", doc_id) | |
| # Run the ingest pipeline | |
| chunk_count = await ingest_service.process_document_from_bytes( | |
| doc_id, | |
| args.title, | |
| pdf_bytes, | |
| session=session, | |
| client=client, | |
| ) | |
| logger.info("Done! document_id=%s, chunks=%d", doc_id, chunk_count) | |
| await close_db() | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |