Spaces:
Build error

File size: 5,014 Bytes
549e591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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 <document_id>

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 <document_id>")
        sys.exit(1)
    asyncio.run(main(sys.argv[1]))