Spaces:
Build error

File size: 5,014 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
"""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())