"""Run ONLY the Document Graph analysis on an already-indexed document — skips the entire text-extraction / chunking / question-extraction / chunk- embedding pipeline (which already ran and is stored). Turns a ~15-min full re-ingest into a ~2-3-min graph-only run, so the diagram/table/formula pipeline can be iterated on without re-embedding text every time. Usage: python app_tools/run_graph_analysis.py Reuses the exact same code path a normal ingest uses for the graph step (IngestService._run_document_graph_analysis), just fed from the DB instead of a fresh extraction. Idempotent: re-running matches existing elements and versions them (content history), never duplicates. NOTE: this makes real OpenRouter vision calls (cost) and local embedding calls. The vision GATE per page is cached, so re-runs are cheaper than the first. Candidate pages here are those with an embedded raster image (the OCR-history half of the normal filter isn't available outside a live ingest — a page whose only visual is vector-drawn may be missed, same known limitation as the main pipeline). """ import asyncio import sys import time from sqlalchemy import text from app.database import close_db, get_rag_session, init_db from app.dependencies import get_http_client, get_ingest_service, init_services, shutdown_services async def _counts(session, document_id: str) -> dict: row = (await session.execute(text(""" SELECT COUNT(*) FILTER (WHERE element_type = 'diagram') AS diagrams, COUNT(*) FILTER (WHERE element_type = 'table') AS tables, COUNT(*) FILTER (WHERE element_type = 'formula') AS formulas, COUNT(*) FILTER (WHERE element_type = 'paragraph') AS paragraphs FROM rag_elements WHERE document_id = CAST(:d AS uuid) AND deleted_at IS NULL """), {"d": document_id})).mappings().first() rels = (await session.execute(text(""" SELECT COUNT(*) FROM rag_element_relationships WHERE from_element_id IN (SELECT id FROM rag_elements WHERE document_id = CAST(:d AS uuid)) """), {"d": document_id})).scalar() embs = (await session.execute(text(""" SELECT COUNT(*) FROM element_embeddings ee JOIN rag_elements e ON e.id = ee.element_id WHERE e.document_id = CAST(:d AS uuid) """), {"d": document_id})).scalar() return {**dict(row), "relationships": rels, "embeddings": embs} async def main(document_id: str) -> None: await init_db() init_services() ingest = get_ingest_service() client = get_http_client() if ingest._cloud_llm is None: print("Cloud LLM (OpenRouter) not configured — graph analysis cannot run.") return async with get_rag_session() as session: doc = (await session.execute( text("SELECT title, s3_key FROM rag_documents WHERE id = CAST(:d AS uuid)"), {"d": document_id}, )).mappings().first() if not doc: print(f"No rag_documents row for {document_id}") return if not doc["s3_key"]: print(f"Document {document_id} has no s3_key — cannot fetch the PDF.") return rows = (await session.execute( text("SELECT id, chunk_index, page_number FROM rag_chunks " "WHERE document_id = CAST(:d AS uuid) ORDER BY chunk_index"), {"d": document_id}, )).mappings().all() if not rows: print(f"Document {document_id} has no chunks — run a normal ingest first.") return chunks = [{"chunk_index": r["chunk_index"], "page_number": r["page_number"]} for r in rows] chunk_db_ids = {r["chunk_index"]: str(r["id"]) for r in rows} try: title = doc["title"] except Exception: title = document_id print(f"Document: {title}") before = await _counts(session, document_id) print(f"Before: {before}") print("Downloading PDF from S3...") pdf_bytes = await ingest._download_from_s3(doc["s3_key"]) async def _emit(ev: dict) -> None: step = ev.get("step", "") if step.startswith("graph"): print(f" [{ev.get('pct','?')}%] {ev.get('msg','')}") t0 = time.monotonic() # raw_pages=[] -> candidate filter falls back to embedded-image pages only. result = await ingest._run_document_graph_analysis( document_id, pdf_bytes, chunks, chunk_db_ids, raw_pages=[], session=session, client=client, _emit=_emit, ) elapsed = time.monotonic() - t0 after = await _counts(session, document_id) print(f"\nResult: {result}") print(f"After: {after}") print(f"Elapsed: {elapsed:.0f}s") await shutdown_services() await close_db() if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python app_tools/run_graph_analysis.py ") sys.exit(1) asyncio.run(main(sys.argv[1]))