"""Re-ingest a document from local PDF — connection-safe for long OCR.""" import argparse import asyncio import logging import sys import io import uuid import json from pathlib import Path from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit # Force UTF-8 encoding for Windows console sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", stream=sys.stdout, ) # OCR cache directory OCR_CACHE_DIR = Path("_OCR_CACHE") OCR_CACHE_DIR.mkdir(exist_ok=True) def get_ocr_cache_path(pdf_path: str) -> Path: """Get cache file path for a PDF's OCR output.""" import hashlib pdf_hash = hashlib.sha256(Path(pdf_path).resolve().as_posix().encode()).hexdigest()[:16] return OCR_CACHE_DIR / f"ocr_{pdf_hash}.json" def load_ocr_cache(pdf_path: str) -> list[tuple[int, str]] | None: """Load cached OCR output if available.""" cache_file = get_ocr_cache_path(pdf_path) if cache_file.exists(): try: with open(cache_file) as f: data = json.load(f) logging.getLogger(__name__).info(f"Loaded OCR cache from {cache_file} ({len(data)} pages)") return [(int(k), v) for k, v in data.items()] except Exception as e: logging.getLogger(__name__).warning(f"Failed to load OCR cache: {e}") return None def save_ocr_cache(pdf_path: str, pages: list[tuple[int, str]]) -> None: """Save OCR output to cache for future reuse.""" cache_file = get_ocr_cache_path(pdf_path) try: data = {str(page_num): text for page_num, text in pages} with open(cache_file, 'w') as f: json.dump(data, f) logging.getLogger(__name__).info(f"Saved OCR cache to {cache_file}") except Exception as e: logging.getLogger(__name__).warning(f"Failed to save OCR cache: {e}") def _normalise_asyncpg_url(raw: str) -> str: """Normalize DB URL for asyncpg compatibility. - Convert postgresql:// -> postgresql+asyncpg:// - Remove unsupported channel_binding - Convert sslmode=require -> ssl=require """ url = raw.strip().strip('"') if url.startswith("postgresql://") or url.startswith("postgres://"): url = url.replace("postgresql://", "postgresql+asyncpg://", 1) url = url.replace("postgres://", "postgresql+asyncpg://", 1) if "?" not in url: return url split = urlsplit(url) query_pairs = parse_qsl(split.query, keep_blank_values=True) normalized_pairs: list[tuple[str, str]] = [] ssl_value = None for key, value in query_pairs: key_lower = key.lower() if key_lower == "channel_binding": continue if key_lower == "sslmode": ssl_value = value or "require" continue normalized_pairs.append((key, value)) has_ssl = any(k.lower() == "ssl" for k, _ in normalized_pairs) if ssl_value is not None and not has_ssl: normalized_pairs.append(("ssl", ssl_value)) return urlunsplit(( split.scheme, split.netloc, split.path, urlencode(normalized_pairs), split.fragment, )) def _mask_db_target(url: str) -> str: """Return safe db target label without credentials.""" split = urlsplit(url) host = split.hostname or "unknown-host" db_name = split.path.lstrip("/") or "unknown-db" return f"{host}/{db_name}" async def main(): import unicodedata import httpx from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from sqlalchemy import text as sql_text from app.config import get_settings from app.services.embed import EmbedService from app.services.llm import LLMService from app.services.ingest import ( _extract_text_from_bytes, _normalize_arabic_text, _sanitize_for_embedding, IngestService, ) from app.services.heading_detector import detect_headings_async, build_page_heading_map from app.services.text_cleaning import TextCleaningService parser = argparse.ArgumentParser(description="Re-ingest a document from a local PDF") parser.add_argument("--clean", action="store_true", help="Delete existing rag_chunks (and rag_questions) before re-ingesting") parser.add_argument("--doc-id", type=str, default=None, help="Document UUID to re-ingest (auto-detect if not provided)") parser.add_argument("--pdf-path", type=str, default="_RAG/DERASAT_6prim_T2.pdf", help="Path to local PDF file") parser.add_argument("--skip-ocr-cache", action="store_true", help="Force re-run OCR even if cache exists (useful for testing)") parser.add_argument("--db-target", choices=["rag", "primary"], default="rag", help="Database target: rag=DATABASE_RAG_URL (default), primary=DATABASE_URL") args = parser.parse_args() settings = get_settings() if args.db_target == "rag" and settings.DATABASE_RAG_URL.strip().strip('"'): raw_db_url = settings.DATABASE_RAG_URL else: raw_db_url = settings.DATABASE_URL db_url = _normalise_asyncpg_url(raw_db_url) print(f"DB target: {args.db_target} -> {_mask_db_target(db_url)}", flush=True) engine = create_async_engine(db_url, pool_recycle=120) async_session_factory = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) embed_service = EmbedService() llm_service = LLMService() embed_model = settings.OLLAMA_EMBED_MODEL with open(args.pdf_path, "rb") as f: pdf_bytes = f.read() print(f"PDF size: {len(pdf_bytes)} bytes", flush=True) # ── Auto-detect or create document ── doc_id = args.doc_id async with async_session_factory() as session: if not doc_id: # Try to find existing document by title pdf_filename = Path(args.pdf_path).stem # filename without extension result = await session.execute( sql_text("SELECT id FROM rag_documents WHERE title ILIKE :name LIMIT 1"), {"name": f"%{pdf_filename}%"} ) row = result.fetchone() if row: doc_id = str(row[0]) print(f"Auto-detected document ID: {doc_id}", flush=True) else: # Create new document doc_id = str(uuid.uuid4()) await session.execute( sql_text(""" INSERT INTO rag_documents (id, title, document_type, status, grade_level, chunk_count, created_at, updated_at) VALUES (:id, :title, :doc_type, 'PROCESSING', :grade, 0, NOW(), NOW()) """), { "id": doc_id, "title": pdf_filename, "doc_type": "TEXTBOOK", "grade": "PRIMARY_6", } ) await session.commit() print(f"Created new document ID: {doc_id}", flush=True) else: # Verify document exists result = await session.execute( sql_text("SELECT id FROM rag_documents WHERE id = :id"), {"id": doc_id} ) if not result.fetchone(): print(f"ERROR: Document {doc_id} not found in database", flush=True) sys.exit(1) # ── Optional clean: delete existing chunks (and questions if table exists) ── if args.clean: async with async_session_factory() as session: try: await session.execute( sql_text("DELETE FROM rag_questions WHERE document_id = CAST(:id AS uuid)"), {"id": doc_id}, ) print("Deleted existing rag_questions", flush=True) except Exception: pass # Table may not exist yet result = await session.execute( sql_text("DELETE FROM rag_chunks WHERE document_id = CAST(:id AS uuid)"), {"id": doc_id}, ) await session.commit() print(f"Deleted {result.rowcount} existing rag_chunks", flush=True) async with async_session_factory() as session: await session.execute( sql_text("UPDATE rag_documents SET status = 'PROCESSING', chunk_count = 0 WHERE id = :id"), {"id": doc_id}, ) await session.commit() print("Status: PROCESSING", flush=True) # ── OCR with caching ── print("Checking OCR cache...", flush=True) pages = None if not args.skip_ocr_cache: pages = load_ocr_cache(args.pdf_path) if pages is None: print("Starting text extraction with Surya OCR (this may take ~18 minutes)...", flush=True) pages = await asyncio.to_thread(_extract_text_from_bytes, pdf_bytes) print(f"Extracted {len(pages)} pages", flush=True) save_ocr_cache(args.pdf_path, pages) else: print(f"Using cached OCR output ({len(pages)} pages)", flush=True) # DEBUG: Show raw OCR output from first page if pages: try: print(f"\n=== RAW OCR OUTPUT (page 1, first 200 chars) ===") print(pages[0][1][:200]) print("=" * 50 + "\n", flush=True) except Exception: pass # Initialize text cleaner text_cleaner = TextCleaningService() clean_pages = [] for page_num, page_text in pages: # Unicode normalization t = unicodedata.normalize("NFKC", page_text) # Text cleaning pipeline (merge lines, remove noise, normalize Arabic) t = text_cleaner.clean(t) # Legacy Arabic normalization (kept for backward compatibility) t = _normalize_arabic_text(t) # Sanitize for embedding t = _sanitize_for_embedding(t) if t: clean_pages.append((page_num, t)) total_chars = sum(len(t) for _, t in clean_pages) print(f"Clean pages: {len(clean_pages)}, total chars: {total_chars}", flush=True) # Detect section headings with LLM refinement async with httpx.AsyncClient(timeout=300.0) as llm_client: headings = await detect_headings_async( pdf_bytes, clean_pages, llm_service=llm_service, client=llm_client, ) page_headings: dict[int, str] = {} if headings: page_headings = build_page_heading_map(headings, total_pages=len(pages)) print(f"Detected {len(headings)} section headings:", flush=True) for h in headings: print(f" p{h.page_num}: {h.title}", flush=True) else: print("No section headings detected", flush=True) ingest_service = IngestService(embed_service, llm_service=llm_service) chunks = ingest_service._chunk_text_with_pages(clean_pages, page_headings=page_headings or None) print(f"Chunks: {len(chunks)}", flush=True) indexed = 0 skipped = 0 async with httpx.AsyncClient(timeout=120.0) as client: for chunk in chunks: content = chunk["content"] if not content: skipped += 1 continue if chunk["chunk_index"] == 0: try: print(f"First chunk (100 chars): {content[:100]!r}", flush=True) except UnicodeEncodeError: print(f"First chunk (100 chars): [Arabic text, {len(content)} chars total]", flush=True) try: result = await embed_service.embed(content, client=client) except Exception as e: print(f"Skipping chunk {chunk['chunk_index']} -- embed failed: {e}", flush=True) skipped += 1 continue vec_literal = EmbedService.to_vector_literal(result.embedding) chunk_id = str(uuid.uuid4()) async with async_session_factory() as session: await session.execute( sql_text(f""" INSERT INTO rag_chunks ( id, document_id, chunk_index, page_number, content, token_count, section_title, content_type, question_count, has_exercises, text_quality_score, embedding, created_at ) VALUES ( :id, :doc_id, :idx, :page, :content, :tokens, :section, :content_type, :q_count, :has_ex, :quality_score, '{vec_literal}'::vector, NOW() ) ON CONFLICT (document_id, chunk_index) DO UPDATE SET content = EXCLUDED.content, embedding = EXCLUDED.embedding, token_count = EXCLUDED.token_count, section_title = EXCLUDED.section_title, content_type = EXCLUDED.content_type, question_count = EXCLUDED.question_count, has_exercises = EXCLUDED.has_exercises, text_quality_score = EXCLUDED.text_quality_score """), { "id": chunk_id, "doc_id": doc_id, "idx": chunk["chunk_index"], "page": chunk.get("page_number"), "content": content, "tokens": chunk["token_count"], "section": chunk.get("section_title"), "content_type": chunk.get("content_type"), "q_count": chunk.get("question_count", 0), "has_ex": chunk.get("has_exercises", False), "quality_score": chunk.get("text_quality_score", 0.5), }, ) await session.commit() chunk["_db_id"] = chunk_id indexed += 1 if indexed % 10 == 0: print(f" {indexed}/{len(chunks)} chunks stored", flush=True) # ── Extract questions per section ──────────────────────────────────────── from app.services.question_extractor import QuestionExtractorService extractor = QuestionExtractorService(llm_service) sections: dict[str | None, dict] = {} for chunk in chunks: if "_db_id" not in chunk: continue sec = chunk.get("section_title") if sec not in sections: sections[sec] = { "first_chunk_id": chunk["_db_id"], "first_page": chunk.get("page_number"), "parts": [], } sections[sec]["parts"].append(chunk["content"]) questions_total = 0 async with httpx.AsyncClient(timeout=120.0) as llm_client2: for section_title, sec_data in sections.items(): section_text = "\n\n".join(sec_data["parts"]) qs = await extractor.extract_from_section(section_text, section_title, llm_client2) if not qs: continue async with async_session_factory() as session: for q in qs: await session.execute( sql_text(""" INSERT INTO rag_questions ( id, document_id, chunk_id, section_title, page_number, question_text, question_type, answer_text, created_at ) VALUES ( :id, CAST(:doc_id AS uuid), CAST(:chunk_id AS uuid), :section, :page, :qtext, :qtype, :answer, NOW() ) """), { "id": str(uuid.uuid4()), "doc_id": doc_id, "chunk_id": sec_data["first_chunk_id"], "section": section_title, "page": sec_data["first_page"], "qtext": q["text"], "qtype": q.get("type"), "answer": q.get("answer"), }, ) questions_total += 1 await session.commit() print(f"Questions extracted and stored: {questions_total}", flush=True) async with async_session_factory() as session: await session.execute( sql_text(""" UPDATE rag_documents SET status = 'INDEXED', chunk_count = :cnt, embedding_model = :model, indexed_at = NOW() WHERE id = :id """), {"id": doc_id, "cnt": indexed, "model": embed_model}, ) await session.commit() print(f"Done! {indexed} chunks indexed ({skipped} skipped)", flush=True) await engine.dispose() if __name__ == "__main__": asyncio.run(main())