rag-service/.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ venv
2
+ __pycache__
3
+ *.pyc
4
+ .env
5
+ .DS_Store
rag-service/Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies required for some Python packages (e.g. FAISS/Torch)
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ build-essential \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ COPY requirements.txt .
11
+
12
+ # Upgrade pip
13
+ RUN pip install --no-cache-dir --upgrade pip
14
+
15
+ # Install CPU-only PyTorch first
16
+ RUN pip install --no-cache-dir \
17
+ torch --index-url https://download.pytorch.org/whl/cpu
18
+
19
+ # Install remaining dependencies
20
+ RUN pip install --no-cache-dir -r requirements.txt
21
+
22
+ COPY . .
23
+
24
+ EXPOSE 5000
25
+
26
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000"]
rag-service/__pycache__/main.cpython-310.pyc ADDED
Binary file (32.7 kB). View file
 
rag-service/crawler/README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Crawler Agent (RAG DB Ingestion) — Architecture
2
+
3
+ This folder defines a **crawler agent** architecture for ingesting **database-backed knowledge** into a RAG index.
4
+
5
+ The goal is to support "RAG over DBs" by:
6
+
7
+ - Connecting to a data source (SQLite/Postgres/MySQL/etc.)
8
+ - Extracting records (tables, rows, views, or query results)
9
+ - Converting records into LangChain `Document`s
10
+ - Chunking + embedding documents
11
+ - Writing them into a vector store (FAISS now, pluggable later)
12
+
13
+ ## Components
14
+
15
+ ### 1) `DatabaseConnector`
16
+ Responsible for connecting to a database and yielding **records** in a stable streaming fashion.
17
+
18
+ Key requirements:
19
+ - Streaming iteration (no full table loads)
20
+ - Bounded memory usage
21
+ - Back-pressure friendly (generator interface)
22
+ - Sanitized metadata (no secrets, no PII by default)
23
+
24
+ ### 2) `DocumentBuilder`
25
+ Responsible for converting DB records into LangChain `Document`s:
26
+ - `page_content`: the text representation used by embeddings/search
27
+ - `metadata`: provenance fields (db type, table, primary key/id, etc.)
28
+
29
+ ### 3) `CrawlerAgent`
30
+ Coordinates:
31
+ - Connector → DocumentBuilder → (optional) chunking → vector store write
32
+
33
+ The agent should be runnable in two modes:
34
+ - **one-shot**: run once and exit (CI, cron, manual)
35
+ - **daemon**: run periodically (future)
36
+
37
+ ## Initial implementation (this PR)
38
+
39
+ This PR provides:
40
+ - A generic connector interface
41
+ - A `MongoDBConnector` example (optional dependency: `pymongo`) for unstructured docs
42
+ - A simple `SQLiteConnector` example (stdlib `sqlite3`)
43
+ - PDF text extraction support when a record contains a PDF blob (bytes or base64)
44
+ - Minimal tests ensuring we can extract documents safely
45
+
46
+ ## Quick demo (for PR screen recording)
47
+
48
+ To demonstrate **DB → PDF → RAG** end-to-end locally:
49
+
50
+ 1. Install deps (plus optional MongoDB client):
51
+ - `python -m pip install -r requirements.txt`
52
+ - `python -m pip install pymongo`
53
+ 2. Set env vars for your MongoDB collection:
54
+ - `MONGODB_URI=...`
55
+ - `MONGO_DB=...`
56
+ - `MONGO_COLLECTION=...`
57
+ 3. Run:
58
+ - `python scripts/demo_mongodb_pdf_rag.py`
59
+
60
+ The script connects to MongoDB, extracts PDF blobs to text, chunks + embeds into FAISS, then runs a sample similarity query and prints the top match.
61
+
62
+ Future work:
63
+ - Firebase/Firestore connector (optional deps)
64
+ - Postgres/MySQL connectors (optional deps)
65
+ - Incremental sync (watermarks, updated_at, row hashes)
66
+ - Persistence for vector stores (disk or DB)
67
+ - Endpoints to trigger ingestion
rag-service/crawler/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .agent import CrawlerAgent
2
+ from .mongodb_connector import MongoDBConnector
3
+ from .sqlite_connector import SQLiteConnector
4
+
5
+ __all__ = ["CrawlerAgent", "MongoDBConnector", "SQLiteConnector"]
rag-service/crawler/agent.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Iterator
5
+
6
+ from .base import DatabaseConnector, record_to_text
7
+ from .pdf_extractor import extract_pdf_text, maybe_decode_pdf_bytes
8
+
9
+
10
+ try:
11
+ from langchain_core.documents import Document # type: ignore
12
+ except Exception: # pragma: no cover
13
+ from langchain.schema import Document # type: ignore
14
+
15
+
16
+ @dataclass
17
+ class CrawlerAgent:
18
+ connector: DatabaseConnector
19
+ source_name: str
20
+
21
+ def iter_documents(self) -> Iterator[Document]:
22
+ for record in self.connector.iter_records():
23
+ pdf_bytes = maybe_decode_pdf_bytes(record.fields)
24
+ if pdf_bytes is not None:
25
+ content = extract_pdf_text(pdf_bytes)
26
+ else:
27
+ content = record_to_text(record)
28
+ if not content:
29
+ continue
30
+
31
+ metadata = {
32
+ "source": record.source,
33
+ "entity": record.entity,
34
+ "record_id": record.record_id,
35
+ }
36
+ yield Document(page_content=content, metadata=metadata)
rag-service/crawler/base.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, Iterator, Mapping, Optional, Protocol
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Record:
9
+ source: str
10
+ entity: str
11
+ record_id: str
12
+ fields: Mapping[str, object]
13
+
14
+
15
+ class DatabaseConnector(Protocol):
16
+ def iter_records(self) -> Iterator[Record]:
17
+ ...
18
+
19
+
20
+ def safe_str(value: object, max_len: int = 4000) -> str:
21
+ if isinstance(value, (bytes, bytearray, memoryview)):
22
+ size = len(value) # type: ignore[arg-type]
23
+ return f"[binary {size} bytes]"
24
+ text = "" if value is None else str(value)
25
+ if len(text) > max_len:
26
+ return text[: max_len - 3] + "..."
27
+ return text
28
+
29
+
30
+ def record_to_text(record: Record, field_order: Optional[Iterable[str]] = None) -> str:
31
+ keys = list(record.fields.keys())
32
+ if field_order:
33
+ ordered = [k for k in field_order if k in record.fields]
34
+ unordered = [k for k in keys if k not in ordered]
35
+ keys = ordered + unordered
36
+
37
+ lines = [f"{k}: {safe_str(record.fields.get(k))}" for k in keys]
38
+ return "\n".join(lines).strip()
rag-service/crawler/mongodb_connector.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Iterator, Mapping, Optional
5
+
6
+ from .base import Record
7
+
8
+
9
+ @dataclass
10
+ class MongoDBConnector:
11
+ """
12
+ MongoDB connector intended for unstructured "documents that may contain PDFs".
13
+
14
+ Notes:
15
+ - Requires optional dependency: `pymongo`
16
+ - For PDF blobs, common patterns are:
17
+ - Store raw bytes directly in a document field (BSON Binary → bytes in Python)
18
+ - Store base64 text in a field
19
+ - Store in GridFS and reference file id (future extension)
20
+ """
21
+
22
+ uri: str
23
+ database: str
24
+ collection: str
25
+ query: Mapping[str, Any] = field(default_factory=dict)
26
+ projection: Optional[Mapping[str, Any]] = None
27
+ limit: Optional[int] = None
28
+
29
+ def iter_records(self) -> Iterator[Record]:
30
+ try:
31
+ from pymongo import MongoClient # type: ignore
32
+ except Exception as exc: # pragma: no cover
33
+ raise RuntimeError(
34
+ "MongoDBConnector requires pymongo. Install with: pip install pymongo"
35
+ ) from exc
36
+
37
+ client = MongoClient(self.uri)
38
+ try:
39
+ coll = client[self.database][self.collection]
40
+ cursor = coll.find(dict(self.query), self.projection)
41
+ if self.limit is not None:
42
+ cursor = cursor.limit(int(self.limit))
43
+ for doc in cursor:
44
+ record_id = str(doc.get("_id", ""))
45
+ fields: Mapping[str, object] = dict(doc)
46
+ yield Record(
47
+ source="mongodb",
48
+ entity=self.collection,
49
+ record_id=record_id,
50
+ fields=fields,
51
+ )
52
+ finally:
53
+ client.close()
rag-service/crawler/pdf_extractor.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ from typing import Mapping, Optional
6
+
7
+
8
+ def maybe_decode_pdf_bytes(fields: Mapping[str, object]) -> Optional[bytes]:
9
+ """
10
+ Best-effort extraction of PDF bytes from an unstructured record.
11
+
12
+ Supported shapes:
13
+ - bytes/bytearray/memoryview in a field named like "pdf", "pdf_bytes", "document", etc.
14
+ - base64-encoded string in a field named like "pdf_base64", "pdf", etc.
15
+
16
+ This is intentionally heuristic so MongoDB/Firestore-style documents can work
17
+ without rigid schemas.
18
+ """
19
+ candidate_keys = [
20
+ "pdf_bytes",
21
+ "pdf",
22
+ "document",
23
+ "file",
24
+ "blob",
25
+ "attachment",
26
+ "content",
27
+ "data",
28
+ "pdf_base64",
29
+ ]
30
+
31
+ for key in candidate_keys:
32
+ if key not in fields:
33
+ continue
34
+
35
+ value = fields.get(key)
36
+ if isinstance(value, bytes):
37
+ return value
38
+ if isinstance(value, bytearray):
39
+ return bytes(value)
40
+ if isinstance(value, memoryview):
41
+ return value.tobytes()
42
+ if isinstance(value, str):
43
+ text = value.strip()
44
+ if not text:
45
+ continue
46
+ try:
47
+ return base64.b64decode(text, validate=True)
48
+ except Exception:
49
+ continue
50
+
51
+ return None
52
+
53
+
54
+ def extract_pdf_text(
55
+ pdf_bytes: bytes,
56
+ *,
57
+ max_pages: int = 50,
58
+ max_chars: int = 250_000,
59
+ ) -> str:
60
+ """
61
+ Extract text from PDF bytes using pypdf.
62
+
63
+ Limits are defensive to keep ingestion bounded for very large PDFs.
64
+ """
65
+ from pypdf import PdfReader # local import to keep module import-light
66
+
67
+ reader = PdfReader(io.BytesIO(pdf_bytes))
68
+
69
+ chunks: list[str] = []
70
+ for idx, page in enumerate(reader.pages):
71
+ if idx >= max_pages:
72
+ break
73
+ text = page.extract_text() or ""
74
+ if text:
75
+ chunks.append(text)
76
+ if sum(len(c) for c in chunks) >= max_chars:
77
+ break
78
+
79
+ return "\n".join(chunks).strip()
80
+
rag-service/crawler/sqlite_connector.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sqlite3
4
+ from dataclasses import dataclass
5
+ from typing import Iterator, Mapping
6
+
7
+ from .base import Record
8
+
9
+
10
+ def _validate_identifier(name: str, label: str) -> str:
11
+ if not name or not isinstance(name, str):
12
+ raise ValueError(f"{label} must be a non-empty string")
13
+ if not name.replace("_", "").isalnum():
14
+ raise ValueError(f"{label} contains unsupported characters: {name!r}")
15
+ return name
16
+
17
+
18
+ @dataclass
19
+ class SQLiteConnector:
20
+ db_path: str
21
+ table: str
22
+ id_column: str = "id"
23
+
24
+ def iter_records(self) -> Iterator[Record]:
25
+ table = _validate_identifier(self.table, "table")
26
+ id_column = _validate_identifier(self.id_column, "id_column")
27
+
28
+ conn = sqlite3.connect(self.db_path)
29
+ conn.row_factory = sqlite3.Row
30
+ try:
31
+ cursor = conn.execute(f"SELECT * FROM {table}")
32
+ for row in cursor:
33
+ fields: Mapping[str, object] = dict(row)
34
+ record_id = str(fields.get(id_column, ""))
35
+ yield Record(
36
+ source="sqlite",
37
+ entity=table,
38
+ record_id=record_id,
39
+ fields=fields,
40
+ )
41
+ finally:
42
+ conn.close()
rag-service/main.py ADDED
@@ -0,0 +1,2578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, HTTPException, File, UploadFile, Form
2
+ from fastapi.responses import JSONResponse, StreamingResponse
3
+ from fastapi.exceptions import RequestValidationError
4
+ from pydantic import BaseModel, Field, field_validator
5
+ from pathlib import Path
6
+ from uuid import UUID
7
+ from contextlib import contextmanager
8
+ from langchain_community.vectorstores import FAISS
9
+ from langchain_community.embeddings import HuggingFaceEmbeddings
10
+ from dotenv import load_dotenv
11
+ from rank_bm25 import BM25Okapi
12
+ from pdf_parse_worker import _extract_pdf_text_worker
13
+ from langchain_community.vectorstores import FAISS
14
+ import numpy as np
15
+ import json
16
+ import uuid
17
+ import uvicorn
18
+ import torch
19
+ import multiprocessing
20
+ import os
21
+ import secrets
22
+ import shutil
23
+ from transformers import (
24
+ AutoConfig,
25
+ AutoTokenizer,
26
+ AutoModelForSeq2SeqLM,
27
+ AutoModelForCausalLM,
28
+ TextIteratorStreamer,
29
+ )
30
+ import threading
31
+ import time
32
+ import logging
33
+ import re
34
+
35
+ try: # pragma: no cover
36
+ import fcntl # type: ignore
37
+ except Exception: # pragma: no cover
38
+ fcntl = None
39
+
40
+ try: # pragma: no cover
41
+ import msvcrt # type: ignore
42
+ except Exception: # pragma: no cover
43
+ msvcrt = None
44
+
45
+ load_dotenv()
46
+
47
+ # ── Logger (must be defined before exception handlers that use it) ─────────────
48
+ logger = logging.getLogger("pdf_qa_rag")
49
+ logging.basicConfig(
50
+ level=os.getenv("LOG_LEVEL", "INFO"),
51
+ format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
52
+ )
53
+
54
+ app = FastAPI()
55
+
56
+ BASE_DIR = Path(__file__).resolve().parent.parent
57
+ UPLOADS_DIR = (BASE_DIR / "uploads").resolve()
58
+ DATA_DIR = (BASE_DIR / "rag-service" / "data").resolve()
59
+ FAISS_DIR = DATA_DIR / "faiss"
60
+ SESSIONS_FILE = DATA_DIR / "sessions.json"
61
+ PERSIST_PATH = DATA_DIR
62
+ SESSION_REGISTRY_FILE = PERSIST_PATH / "session_registry.json"
63
+ SESSION_REGISTRY_LOCK_FILE = PERSIST_PATH / "session_registry.lock"
64
+
65
+ os.makedirs(DATA_DIR, exist_ok=True)
66
+ os.makedirs(FAISS_DIR, exist_ok=True)
67
+
68
+ def load_sessions():
69
+ if SESSIONS_FILE.exists():
70
+ try:
71
+ with open(SESSIONS_FILE, "r", encoding="utf-8") as f:
72
+ data = json.load(f)
73
+ for sid, meta in data.items():
74
+ meta["lock"] = threading.Lock()
75
+ meta["vectorstore"] = None
76
+ return data
77
+ except Exception as e:
78
+ logger.error(f"Failed to load sessions: {e}")
79
+ return {}
80
+
81
+ def save_sessions_unlocked():
82
+ try:
83
+ data = {}
84
+ for sid, meta in sessions.items():
85
+ data[sid] = {
86
+ "created_at": meta.get("created_at"),
87
+ "last_accessed": meta.get("last_accessed"),
88
+ "documents": meta.get("documents", []),
89
+ "retrieval_cache": meta.get("retrieval_cache", {}),
90
+ "chat": meta.get("chat", []),
91
+ "session_secret": meta.get("session_secret"),
92
+ }
93
+ with open(SESSIONS_FILE, "w", encoding="utf-8") as f:
94
+ json.dump(data, f)
95
+ except Exception as e:
96
+ logger.error(f"Failed to save sessions: {e}")
97
+
98
+ # Global session store
99
+ sessions = load_sessions()
100
+ def update_processing_progress(session_id, stage, progress):
101
+ payload = {
102
+ "stage": stage,
103
+ "progress": progress,
104
+ "updated_at": now_ts(),
105
+ }
106
+ with sessions_lock:
107
+ meta = sessions.get(session_id)
108
+ if not meta:
109
+ return
110
+ meta["processing_progress"] = payload
111
+
112
+ INTERNAL_RAG_TOKEN = os.getenv("INTERNAL_RAG_TOKEN", "").strip()
113
+
114
+ PDF_PARSE_TIMEOUT_SECONDS = int(os.getenv("PDF_PARSE_TIMEOUT_SECONDS", "20"))
115
+ MAX_PDF_PAGES = int(os.getenv("MAX_PDF_PAGES", "200"))
116
+ MAX_PDF_EXTRACT_CHARS = int(os.getenv("MAX_PDF_EXTRACT_CHARS", "400000"))
117
+
118
+ try:
119
+ from langchain_core.documents import Document # type: ignore
120
+ except Exception: # pragma: no cover
121
+ from langchain.schema import Document # type: ignore
122
+
123
+ def internal_token_valid(provided: str | None, expected: str) -> bool:
124
+ if not expected:
125
+ return True
126
+ candidate = (provided or "").strip()
127
+ return bool(candidate) and candidate == expected
128
+
129
+
130
+ def generate_session_secret() -> str:
131
+ return secrets.token_urlsafe(32)
132
+
133
+
134
+ def standard_error_response(status_code: int, detail: str, **extra):
135
+ payload = {
136
+ "error": detail,
137
+ "detail": detail,
138
+ **extra,
139
+ }
140
+ return JSONResponse(status_code=status_code, content=payload)
141
+
142
+ def extract_pdf_documents_sandboxed(pdf_path: str, filename: str):
143
+ """
144
+ Parse PDF in a separate process with hard timeout and page/size limits.
145
+
146
+ Returns: List[Document]
147
+ Raises: HTTPException on failure.
148
+ """
149
+ start = time.time()
150
+ ctx = multiprocessing.get_context("spawn")
151
+ out_queue = ctx.Queue(maxsize=1)
152
+ proc = ctx.Process(
153
+ target=_extract_pdf_text_worker,
154
+ args=(pdf_path, MAX_PDF_PAGES, MAX_PDF_EXTRACT_CHARS, out_queue),
155
+ daemon=True,
156
+ )
157
+ proc.start()
158
+ proc.join(timeout=PDF_PARSE_TIMEOUT_SECONDS)
159
+
160
+ if proc.is_alive():
161
+ logger.warning(
162
+ "PDF parse timeout filename=%s timeout_seconds=%s",
163
+ filename,
164
+ PDF_PARSE_TIMEOUT_SECONDS,
165
+ )
166
+ proc.terminate()
167
+ proc.join(timeout=2)
168
+ raise HTTPException(
169
+ status_code=422,
170
+ detail=(
171
+ "PDF parsing timed out. This PDF may be too complex or malformed. "
172
+ "Try a smaller/simpler PDF."
173
+ ),
174
+ )
175
+
176
+ try:
177
+ result = out_queue.get_nowait()
178
+ except Exception:
179
+ raise HTTPException(status_code=400, detail="Unable to read this PDF.")
180
+
181
+ if not isinstance(result, dict) or not result.get("ok"):
182
+ error = (result or {}).get("error") if isinstance(result, dict) else None
183
+ raise HTTPException(status_code=400, detail=error or "Unable to read this PDF.")
184
+
185
+ extracted = result.get("extracted", [])
186
+ extracted_chars = int(result.get("extracted_chars", 0) or 0)
187
+ page_count = int(result.get("page_count", 0) or 0)
188
+ elapsed_ms = int((time.time() - start) * 1000)
189
+
190
+ logger.info(
191
+ "PDF parsed safely filename=%s pages=%s extracted_pages=%s extracted_chars=%s duration_ms=%s",
192
+ filename,
193
+ page_count,
194
+ len(extracted),
195
+ extracted_chars,
196
+ elapsed_ms,
197
+ )
198
+
199
+ docs = []
200
+ for item in extracted:
201
+ page = item.get("page")
202
+ text = (item.get("text") or "").strip()
203
+ if not text:
204
+ continue
205
+ docs.append(
206
+ Document(
207
+ page_content=text,
208
+ metadata={
209
+ "page": page,
210
+ "filename": filename,
211
+ "source": filename,
212
+ },
213
+ )
214
+ )
215
+ if not docs:
216
+ raise HTTPException(status_code=400, detail="No readable text was found in the PDF.")
217
+ return docs
218
+
219
+ @app.middleware("http")
220
+ async def internal_auth_middleware(request: Request, call_next):
221
+ """
222
+ Enforce service-to-service auth for RAG endpoints when INTERNAL_RAG_TOKEN is set.
223
+
224
+ This prevents attackers from bypassing the API gateway's rate limits by calling
225
+ the RAG service directly (for example when port 5000 is accidentally exposed).
226
+ """
227
+ protected_paths = {
228
+ "/process-pdf",
229
+ "/ask",
230
+ "/summarize",
231
+ "/validate-session-write",
232
+ "/sessions/lookup",
233
+ }
234
+
235
+ if INTERNAL_RAG_TOKEN and (
236
+ request.url.path in protected_paths
237
+ or request.url.path.startswith("/processing-status/")
238
+ ):
239
+ provided = request.headers.get("X-Internal-Token")
240
+ if not internal_token_valid(provided, INTERNAL_RAG_TOKEN):
241
+ return standard_error_response(403, "Forbidden")
242
+
243
+ return await call_next(request)
244
+
245
+
246
+ @app.exception_handler(RequestValidationError)
247
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
248
+ errors = [
249
+ {"loc": err["loc"], "msg": err["msg"], "type": err["type"]}
250
+ for err in exc.errors()
251
+ ]
252
+ logger.warning("Request validation failed path=%s errors=%s", request.url.path, errors)
253
+ return standard_error_response(422, "Validation failed", details=errors)
254
+
255
+
256
+ @app.exception_handler(HTTPException)
257
+ async def http_exception_handler(request: Request, exc: HTTPException):
258
+ detail = exc.detail
259
+ if not isinstance(detail, str):
260
+ detail = str(detail)
261
+ return standard_error_response(exc.status_code, detail)
262
+
263
+
264
+ @app.exception_handler(Exception)
265
+ async def global_exception_handler(request: Request, exc: Exception):
266
+ print(f"Unhandled exception: {exc}")
267
+ return standard_error_response(500, "Internal server error. Please try again later.")
268
+
269
+
270
+ # Session storage with metadata and thread safety
271
+
272
+ sessions_lock = threading.Lock()
273
+ model_load_lock = threading.Lock()
274
+ generation_lock = threading.Lock()
275
+
276
+ # Configurable session TTL and max cap
277
+ SESSION_TTL_MINUTES = int(os.getenv("SESSION_TTL_MINUTES", "43200")) # 30 days default for persistence
278
+ MAX_ACTIVE_SESSIONS = int(os.getenv("MAX_ACTIVE_SESSIONS", "1000"))
279
+ MAX_DOCUMENTS_PER_SESSION = int(os.getenv("MAX_DOCUMENTS_PER_SESSION", "5"))
280
+ MAX_CHUNKS_PER_SESSION = int(os.getenv("MAX_CHUNKS_PER_SESSION", "2000"))
281
+ ASK_RETRIEVAL_CANDIDATES = int(os.getenv("ASK_RETRIEVAL_CANDIDATES", "12"))
282
+ ASK_MAX_CONTEXT_CHUNKS = int(os.getenv("ASK_MAX_CONTEXT_CHUNKS", "6"))
283
+ ASK_CHUNKS_PER_DOCUMENT = int(os.getenv("ASK_CHUNKS_PER_DOCUMENT", "2"))
284
+ ASK_DIVERSITY_RANK_LIMIT = int(os.getenv("ASK_DIVERSITY_RANK_LIMIT", "8"))
285
+ ASK_DIVERSITY_SCORE_MULTIPLIER = float(os.getenv("ASK_DIVERSITY_SCORE_MULTIPLIER", "1.8"))
286
+ ASK_DIVERSITY_SCORE_MARGIN = float(os.getenv("ASK_DIVERSITY_SCORE_MARGIN", "0.35"))
287
+ ASK_EVIDENCE_MAX_DISTANCE = float(os.getenv("ASK_EVIDENCE_MAX_DISTANCE", "0.85"))
288
+ ASK_EVIDENCE_MIN_KEYWORD_OVERLAP = int(os.getenv("ASK_EVIDENCE_MIN_KEYWORD_OVERLAP", "2"))
289
+ ASK_EVIDENCE_MIN_KEYWORD_OVERLAP_SHORT_QUERY = int(
290
+ os.getenv("ASK_EVIDENCE_MIN_KEYWORD_OVERLAP_SHORT_QUERY", "1")
291
+ )
292
+ ASK_REQUIRE_CITATIONS = os.getenv("ASK_REQUIRE_CITATIONS", "true").strip().lower() in {
293
+ "1",
294
+ "true",
295
+ "yes",
296
+ "on",
297
+ }
298
+ RETRIEVAL_CACHE_LIMIT = int(os.getenv("RETRIEVAL_CACHE_LIMIT", "25"))
299
+
300
+ # ── Semantic Chunking Config ─────────────────────────────────────────────────
301
+ SEMANTIC_CHUNK_SOFT_MAX = int(os.getenv("SEMANTIC_CHUNK_SOFT_MAX", "1200"))
302
+ SEMANTIC_CHUNK_MERGE_MIN = int(os.getenv("SEMANTIC_CHUNK_MERGE_MIN", "150"))
303
+ SEMANTIC_CHUNK_MERGE_MAX = int(os.getenv("SEMANTIC_CHUNK_MERGE_MAX", "1400"))
304
+ SEMANTIC_CHUNK_SIMILARITY_THRESHOLD = float(
305
+ os.getenv("SEMANTIC_CHUNK_SIMILARITY_THRESHOLD", "0.75")
306
+ )
307
+ SEMANTIC_CHUNK_MERGE_WARN_SECS = float(
308
+ os.getenv("SEMANTIC_CHUNK_MERGE_WARN_SECS", "5.0")
309
+ )
310
+ SEMANTIC_CHUNK_HIERARCHICAL = os.getenv(
311
+ "SEMANTIC_CHUNK_HIERARCHICAL", "true"
312
+ ).strip().lower() in {"1", "true", "yes", "on"}
313
+ QUERY_STOPWORDS = {
314
+ "about", "according", "also", "and", "are", "between", "compare",
315
+ "describe", "does", "document", "documents", "explain", "from", "give",
316
+ "how", "into", "is", "of", "pdf", "pdfs", "related", "summarize",
317
+ "tell", "the", "their", "these", "this", "to", "uploaded", "what", "with",
318
+ }
319
+ RELATIONSHIP_QUERY_TERMS = {
320
+ "associated", "connection", "linked", "relation", "relationship", "related",
321
+ }
322
+ COMPARISON_QUERY_TERMS = {
323
+ "between", "compare", "comparison", "contrast", "difference",
324
+ "different", "role", "versus", "vs",
325
+ }
326
+ OVERVIEW_QUERY_TERMS = {
327
+ "across", "all", "covered", "coverage", "documents", "files",
328
+ "multiple", "overall", "overview", "summarize", "topics",
329
+ }
330
+ INSUFFICIENT_CONTEXT_MESSAGE = "The uploaded documents do not contain enough information to answer this question."
331
+
332
+ UPLOAD_FILENAME_CHARS = frozenset(
333
+ "abcdefghijklmnopqrstuvwxyz"
334
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
335
+ "0123456789"
336
+ "._-"
337
+ )
338
+ FACTUAL_QUESTION_PREFIXES = (
339
+ ("what", "is"), ("what", "are"), ("what", "was"), ("what", "were"),
340
+ ("who", "is"), ("who", "are"), ("who", "was"), ("who", "were"),
341
+ ("where", "is"), ("where", "are"), ("where", "was"), ("where", "were"),
342
+ ("when", "is"), ("when", "are"), ("when", "was"), ("when", "were"),
343
+ )
344
+
345
+
346
+ def now_ts():
347
+ return time.time()
348
+
349
+
350
+ def session_expires_at(last_accessed: float) -> float:
351
+ return last_accessed + (SESSION_TTL_MINUTES * 60)
352
+
353
+
354
+ def normalize_session_id(session_id: str) -> str:
355
+ if not session_id or not str(session_id).strip():
356
+ raise ValueError("Missing session id.")
357
+ return str(UUID(str(session_id).strip()))
358
+
359
+
360
+ def get_session_dir(session_id: str) -> str:
361
+ safe_session_id = normalize_session_id(session_id)
362
+ return os.fspath(PERSIST_PATH / safe_session_id)
363
+
364
+
365
+ @contextmanager
366
+ def session_store_lock(session_id: str):
367
+ safe_session_id = normalize_session_id(session_id)
368
+ PERSIST_PATH.mkdir(parents=True, exist_ok=True)
369
+ lock_path = PERSIST_PATH / f"{safe_session_id}.lock"
370
+ with open(lock_path, "a+b") as lock_file:
371
+ if fcntl:
372
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
373
+ elif msvcrt:
374
+ lock_file.seek(0)
375
+ lock_file.write(b"0")
376
+ lock_file.flush()
377
+ lock_file.seek(0)
378
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
379
+ try:
380
+ yield
381
+ finally:
382
+ if fcntl:
383
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
384
+ elif msvcrt:
385
+ lock_file.seek(0)
386
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
387
+
388
+
389
+ @contextmanager
390
+ def session_registry_lock():
391
+ PERSIST_PATH.mkdir(parents=True, exist_ok=True)
392
+ with open(SESSION_REGISTRY_LOCK_FILE, "a+b") as lock_file:
393
+ if fcntl:
394
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
395
+ elif msvcrt:
396
+ lock_file.seek(0)
397
+ lock_file.write(b"0")
398
+ lock_file.flush()
399
+ lock_file.seek(0)
400
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
401
+ try:
402
+ yield
403
+ finally:
404
+ if fcntl:
405
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
406
+ elif msvcrt:
407
+ lock_file.seek(0)
408
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
409
+
410
+
411
+ def read_session_registry_unlocked() -> dict:
412
+ if not SESSION_REGISTRY_FILE.exists():
413
+ return {}
414
+ try:
415
+ with open(SESSION_REGISTRY_FILE, "r", encoding="utf-8") as registry_file:
416
+ registry = json.load(registry_file)
417
+ return registry if isinstance(registry, dict) else {}
418
+ except Exception:
419
+ logger.exception("Failed to read session registry")
420
+ return {}
421
+
422
+
423
+ def read_session_registry() -> dict:
424
+ with session_registry_lock():
425
+ return read_session_registry_unlocked()
426
+
427
+
428
+ def write_session_registry_unlocked(registry: dict):
429
+ PERSIST_PATH.mkdir(parents=True, exist_ok=True)
430
+ temp_path = SESSION_REGISTRY_FILE.with_suffix(".tmp")
431
+ with open(temp_path, "w", encoding="utf-8") as registry_file:
432
+ json.dump(registry, registry_file, separators=(",", ":"), sort_keys=True)
433
+ os.replace(temp_path, SESSION_REGISTRY_FILE)
434
+
435
+
436
+ def write_session_registry(registry: dict):
437
+ with session_registry_lock():
438
+ write_session_registry_unlocked(registry)
439
+
440
+
441
+ def persist_session_registry_entry(session_id: str, meta: dict):
442
+ with session_registry_lock():
443
+ registry = read_session_registry_unlocked()
444
+ last_accessed = meta.get("last_accessed", now_ts())
445
+ session_dir = get_session_dir(session_id)
446
+ registry[session_id] = {
447
+ "created_at": meta.get("created_at", last_accessed),
448
+ "last_accessed": last_accessed,
449
+ "expires_at": session_expires_at(last_accessed),
450
+ "documents": list(meta.get("documents", [])),
451
+ "session_dir": session_dir,
452
+ "session_secret": meta.get("session_secret"),
453
+ }
454
+ write_session_registry_unlocked(registry)
455
+
456
+
457
+ def remove_persisted_session(session_id: str, session_dir: str | None = None):
458
+ with session_registry_lock():
459
+ registry = read_session_registry_unlocked()
460
+ registry_entry = registry.pop(session_id, None)
461
+ write_session_registry_unlocked(registry)
462
+
463
+ try:
464
+ target_path = Path(get_session_dir(session_id)).resolve()
465
+ if target_path.is_dir() and PERSIST_PATH in target_path.parents:
466
+ shutil.rmtree(target_path)
467
+ except Exception:
468
+ logger.exception("Failed to remove persisted session session_id=%s", session_id)
469
+
470
+
471
+ def cleanup_expired_persisted_sessions(extra_session_dirs: dict | None = None):
472
+ now = now_ts()
473
+ expired_dirs = {}
474
+ with session_registry_lock():
475
+ registry = read_session_registry_unlocked()
476
+ expired_ids = [
477
+ sid
478
+ for sid, entry in registry.items()
479
+ if now > float(entry.get("expires_at", 0) or 0)
480
+ ]
481
+ for sid in extra_session_dirs or {}:
482
+ if sid not in expired_ids:
483
+ expired_ids.append(sid)
484
+
485
+ for sid in expired_ids:
486
+ expired_dirs[sid] = get_session_dir(sid)
487
+ registry.pop(sid, None)
488
+
489
+ if expired_ids:
490
+ write_session_registry_unlocked(registry)
491
+
492
+ for sid, session_dir in expired_dirs.items():
493
+ try:
494
+ target_path = Path(get_session_dir(sid)).resolve()
495
+ if target_path.is_dir() and PERSIST_PATH in target_path.parents:
496
+ shutil.rmtree(target_path)
497
+ except Exception:
498
+ logger.exception("Failed to remove persisted session session_id=%s", sid)
499
+
500
+
501
+ def persist_vectorstore(session_id: str, vectorstore):
502
+ session_dir = get_session_dir(session_id)
503
+ os.makedirs(session_dir, exist_ok=True)
504
+ vectorstore.save_local(session_dir)
505
+ return session_dir
506
+
507
+
508
+ def _recover_session_unlocked(session_id: str):
509
+ registry = read_session_registry()
510
+ entry = registry.get(session_id)
511
+ if not entry:
512
+ return None
513
+
514
+ last_accessed = float(entry.get("last_accessed", 0) or 0)
515
+ if now_ts() > float(entry.get("expires_at", session_expires_at(last_accessed))):
516
+ remove_persisted_session(session_id, entry.get("session_dir"))
517
+ return None
518
+
519
+ session_dir = get_session_dir(session_id)
520
+ if not os.path.isdir(session_dir):
521
+ remove_persisted_session(session_id, session_dir)
522
+ return None
523
+
524
+ try:
525
+ vectorstore = FAISS.load_local(
526
+ session_dir,
527
+ embedding_model,
528
+ allow_dangerous_deserialization=True,
529
+ )
530
+ except Exception:
531
+ logger.exception("Failed to recover persisted session session_id=%s", session_id)
532
+ return None
533
+
534
+ meta = {
535
+ "vectorstore": vectorstore,
536
+ "lock": threading.Lock(),
537
+ "documents": list(entry.get("documents", [])),
538
+ "session_secret": entry.get("session_secret"),
539
+ "session_dir": session_dir,
540
+ "created_at": float(entry.get("created_at", last_accessed) or last_accessed),
541
+ "last_accessed": last_accessed,
542
+ }
543
+ sessions[session_id] = meta
544
+ logger.info("Recovered persisted session session_id=%s", session_id)
545
+ return meta
546
+
547
+
548
+ def cleanup_expired_sessions():
549
+ """
550
+ Remove expired sessions and enforce max session cap.
551
+ """
552
+ expired = []
553
+ expired_dirs = {}
554
+ evicted_count = 0
555
+ active_sessions = 0
556
+ with sessions_lock:
557
+ ttl_seconds = SESSION_TTL_MINUTES * 60
558
+ for sid, meta in list(sessions.items()):
559
+ if now_ts() - meta["last_accessed"] > ttl_seconds:
560
+ expired.append(sid)
561
+ expired_dirs[sid] = meta.get("session_dir")
562
+ for sid in expired:
563
+ del sessions[sid]
564
+ while len(sessions) > MAX_ACTIVE_SESSIONS:
565
+ oldest = min(sessions.items(), key=lambda x: x[1]["created_at"])[0]
566
+ expired_dirs[oldest] = sessions[oldest].get("session_dir")
567
+ del sessions[oldest]
568
+ expired.append(oldest)
569
+ evicted_count += 1
570
+ active_sessions = len(sessions)
571
+ if expired or evicted_count:
572
+ save_sessions_unlocked()
573
+ cleanup_expired_persisted_sessions(expired_dirs)
574
+ if expired or evicted_count:
575
+ logger.info(
576
+ "Session cleanup completed expired=%s evicted=%s active=%s",
577
+ len(expired),
578
+ evicted_count,
579
+ active_sessions,
580
+ )
581
+
582
+
583
+ def _is_session_expired(meta: dict) -> bool:
584
+ ttl_seconds = SESSION_TTL_MINUTES * 60
585
+ return now_ts() - meta["last_accessed"] > ttl_seconds
586
+
587
+
588
+ def _touch_session_unlocked(session_id: str):
589
+ meta = sessions.get(session_id)
590
+ if not meta:
591
+ meta = _recover_session_unlocked(session_id)
592
+ if not meta:
593
+ return None
594
+ # Hard-disable legacy sessions created before session secrets existed.
595
+ # These are effectively "session_id-only" capabilities and must be invalidated
596
+ # to avoid cross-user access.
597
+ if not (meta.get("session_secret") or "").strip():
598
+ session_dir = meta.get("session_dir")
599
+ try:
600
+ del sessions[session_id]
601
+ except Exception:
602
+ pass
603
+ remove_persisted_session(session_id, session_dir)
604
+ logger.info("Invalidated legacy session without secret session_id=%s", session_id)
605
+ return None
606
+ if _is_session_expired(meta):
607
+ session_dir = meta.get("session_dir")
608
+ del sessions[session_id]
609
+ remove_persisted_session(session_id, session_dir)
610
+ logger.info("Session expired session_id=%s", session_id)
611
+ return None
612
+ meta["last_accessed"] = now_ts()
613
+ persist_session_registry_entry(session_id, meta)
614
+ return meta
615
+
616
+
617
+ def _peek_session_unlocked(session_id: str):
618
+ """Read session metadata without refreshing last_accessed.
619
+
620
+ Use this for validation and quota checks where we must not side-effect the
621
+ TTL. An attacker who is rejected at the quota boundary should NOT be able
622
+ to keep an at-cap session alive by spamming the error response.
623
+ Only call _touch_session_unlocked once all checks pass and the operation
624
+ is actually going to succeed.
625
+ """
626
+ meta = sessions.get(session_id)
627
+ if not meta:
628
+ meta = _recover_session_unlocked(session_id)
629
+ if not meta:
630
+ return None
631
+ if not (meta.get("session_secret") or "").strip():
632
+ session_dir = meta.get("session_dir")
633
+ try:
634
+ del sessions[session_id]
635
+ except Exception:
636
+ pass
637
+ remove_persisted_session(session_id, session_dir)
638
+ logger.info("Invalidated legacy session without secret session_id=%s", session_id)
639
+ return None
640
+ if _is_session_expired(meta):
641
+ session_dir = meta.get("session_dir")
642
+ del sessions[session_id]
643
+ remove_persisted_session(session_id, session_dir)
644
+ logger.info("Session expired session_id=%s", session_id)
645
+ return None
646
+ return meta
647
+
648
+
649
+ def _cleanup_expired_sessions_unlocked():
650
+ """Must be called with sessions_lock held."""
651
+ ttl_seconds = SESSION_TTL_MINUTES * 60
652
+ expired = [
653
+ sid for sid, meta in list(sessions.items())
654
+ if now_ts() - meta["last_accessed"] > ttl_seconds
655
+ ]
656
+ for sid in expired:
657
+ session_dir = sessions[sid].get("session_dir")
658
+ del sessions[sid]
659
+ remove_persisted_session(sid, session_dir)
660
+ if expired:
661
+ logger.info("Expired sessions removed count=%s", len(expired))
662
+
663
+
664
+ def _enforce_max_sessions_unlocked():
665
+ while len(sessions) >= MAX_ACTIVE_SESSIONS:
666
+ oldest = min(sessions.items(), key=lambda x: x[1]["created_at"])[0]
667
+ session_dir = sessions[oldest].get("session_dir")
668
+ del sessions[oldest]
669
+ remove_persisted_session(oldest, session_dir)
670
+ logger.info("Evicted oldest session session_id=%s", oldest)
671
+
672
+
673
+ def validate_existing_session(session_id: str):
674
+ if not session_id:
675
+ return None
676
+ with sessions_lock:
677
+ return _touch_session_unlocked(session_id)
678
+
679
+
680
+ def get_session_documents(session_id: str):
681
+ with sessions_lock:
682
+ meta = _touch_session_unlocked(session_id)
683
+ if not meta:
684
+ return None, []
685
+ return meta, list(meta.get("documents", []))
686
+
687
+
688
+ def unique_documents(documents):
689
+ seen = set()
690
+ unique = []
691
+ for doc in documents:
692
+ key = document_dedupe_key(doc)
693
+ if key in seen:
694
+ continue
695
+ seen.add(key)
696
+ unique.append(doc)
697
+ return unique
698
+
699
+
700
+ def document_identity(document):
701
+ return (
702
+ document.metadata.get("document_id")
703
+ or document.metadata.get("filename")
704
+ or document.metadata.get("source")
705
+ or "unknown-document"
706
+ )
707
+
708
+
709
+ def document_display_name(document):
710
+ return (
711
+ document.metadata.get("filename")
712
+ or os.path.basename(document.metadata.get("source", ""))
713
+ or "uploaded document"
714
+ )
715
+
716
+
717
+ def document_dedupe_key(document):
718
+ source = document.metadata.get("filename") or document.metadata.get("source", "")
719
+ page = document.metadata.get("page", "")
720
+ content_key = " ".join(document.page_content.split())[:500]
721
+ return (document_identity(document), source, page, content_key)
722
+
723
+
724
+ def query_keywords(question):
725
+ return {
726
+ token
727
+ for token in re.findall(r"[a-zA-Z0-9]+", question.lower())
728
+ if len(token) > 2 and token not in QUERY_STOPWORDS
729
+ }
730
+
731
+
732
+ def tokenize_text(text):
733
+ return set(re.findall(r"[a-zA-Z0-9]+", text.lower()))
734
+
735
+
736
+ def document_matches_query_terms(document, keywords):
737
+ if not keywords:
738
+ return False
739
+ document_text = " ".join(
740
+ [
741
+ document.page_content,
742
+ document.metadata.get("filename", ""),
743
+ document.metadata.get("source", ""),
744
+ ]
745
+ ).lower()
746
+ document_terms = tokenize_text(document_text)
747
+ return bool(keywords.intersection(document_terms))
748
+
749
+
750
+ def detect_question_intent(question):
751
+ normalized_question = question.lower()
752
+ terms = tokenize_text(normalized_question)
753
+
754
+ if "what is this document about" in normalized_question or "what are these documents about" in normalized_question:
755
+ return "overview"
756
+ if "how is" in normalized_question and terms.intersection(RELATIONSHIP_QUERY_TERMS):
757
+ return "relationship"
758
+ if terms.intersection(RELATIONSHIP_QUERY_TERMS):
759
+ return "relationship"
760
+ if terms.intersection(COMPARISON_QUERY_TERMS):
761
+ return "comparison"
762
+ if (
763
+ terms.intersection(OVERVIEW_QUERY_TERMS)
764
+ or "summarize all" in normalized_question
765
+ or "across uploaded documents" in normalized_question
766
+ ):
767
+ return "overview"
768
+ return "factual"
769
+
770
+ def normalize_query(query: str) -> str:
771
+ return " ".join(query.lower().strip().split())
772
+
773
+ def concise_excerpt(text, max_chars=420):
774
+ normalized_text = " ".join(text.split())
775
+ if len(normalized_text) <= max_chars:
776
+ return normalized_text
777
+ return normalized_text[:max_chars].rsplit(" ", 1)[0] + "..."
778
+
779
+
780
+ def split_sentences(text):
781
+ normalized_text = " ".join(text.split())
782
+ if not normalized_text:
783
+ return []
784
+ return [
785
+ sentence.strip()
786
+ for sentence in re.split(r"(?<=[.!?])\s+", normalized_text)
787
+ if sentence.strip()
788
+ ]
789
+
790
+
791
+ def clean_sentence(sentence):
792
+ return sentence.strip().strip("-* ").rstrip()
793
+
794
+
795
+ def document_sentences(document, max_sentences=3):
796
+ return [
797
+ clean_sentence(sentence)
798
+ for sentence in split_sentences(document.page_content)[:max_sentences]
799
+ if clean_sentence(sentence)
800
+ ]
801
+
802
+
803
+ def group_documents_by_source(documents):
804
+ grouped_documents = {}
805
+ for document in documents:
806
+ source_name = document_display_name(document)
807
+ grouped_documents.setdefault(source_name, []).append(document)
808
+ return grouped_documents
809
+
810
+
811
+ def best_sentences_for_document(documents, question=None, max_sentences=2):
812
+ keywords = query_keywords(question or "")
813
+ scored_sentences = []
814
+
815
+ for document in documents:
816
+ for sentence in document_sentences(document, max_sentences=6):
817
+ sentence_terms = tokenize_text(sentence)
818
+ overlap = len(keywords.intersection(sentence_terms)) if keywords else 0
819
+ scored_sentences.append((overlap, sentence))
820
+
821
+ scored_sentences.sort(key=lambda item: item[0], reverse=True)
822
+ selected_sentences = []
823
+ seen = set()
824
+ for _score, sentence in scored_sentences:
825
+ sentence_key = sentence.lower()
826
+ if sentence_key in seen:
827
+ continue
828
+ seen.add(sentence_key)
829
+ selected_sentences.append(sentence)
830
+ if len(selected_sentences) >= max_sentences:
831
+ break
832
+
833
+ return selected_sentences
834
+
835
+
836
+ def has_grounded_keyword_overlap(question, documents):
837
+ keywords = query_keywords(question)
838
+ if not keywords:
839
+ return True
840
+ for document in documents:
841
+ document_text = " ".join(
842
+ [
843
+ document.page_content,
844
+ document.metadata.get("filename", ""),
845
+ document.metadata.get("source", ""),
846
+ ]
847
+ )
848
+ if keywords.intersection(tokenize_text(document_text)):
849
+ return True
850
+ return False
851
+
852
+
853
+ def best_keyword_overlap_count(question, documents):
854
+ keywords = query_keywords(question)
855
+ if not keywords:
856
+ return 0
857
+ best = 0
858
+ for document in documents:
859
+ document_text = " ".join(
860
+ [
861
+ document.page_content,
862
+ document.metadata.get("filename", ""),
863
+ document.metadata.get("source", ""),
864
+ ]
865
+ )
866
+ overlap = len(keywords.intersection(tokenize_text(document_text)))
867
+ best = max(best, overlap)
868
+ return best
869
+
870
+
871
+ def passes_evidence_gate(question, documents, best_score, intent):
872
+ if not documents:
873
+ return False
874
+ if intent == "overview":
875
+ return True
876
+
877
+ keywords = query_keywords(question)
878
+ if not keywords:
879
+ return True
880
+
881
+ required_overlap = (
882
+ ASK_EVIDENCE_MIN_KEYWORD_OVERLAP_SHORT_QUERY
883
+ if len(keywords) < 4
884
+ else ASK_EVIDENCE_MIN_KEYWORD_OVERLAP
885
+ )
886
+ if best_keyword_overlap_count(question, documents) < required_overlap:
887
+ return False
888
+
889
+ if best_score is None:
890
+ return True
891
+ return best_score <= ASK_EVIDENCE_MAX_DISTANCE
892
+
893
+
894
+ def citation_suffix_for_documents(documents, source_id_by_key):
895
+ if not source_id_by_key:
896
+ return ""
897
+ ids = sorted(
898
+ {
899
+ source_id_by_key.get(document_dedupe_key(document))
900
+ for document in documents
901
+ if document is not None
902
+ }
903
+ )
904
+ ids = [value for value in ids if isinstance(value, int)]
905
+ if not ids:
906
+ return ""
907
+ if len(ids) == 1:
908
+ return f" (Source {ids[0]})"
909
+ joined = ", ".join(str(value) for value in ids)
910
+ return f" (Sources {joined})"
911
+
912
+
913
+ def answer_contains_citation(answer, max_source_id):
914
+ if not answer or not isinstance(answer, str):
915
+ return False
916
+ if not max_source_id or max_source_id < 1:
917
+ return False
918
+ # We accept either "Source 1" or "Sources 1, 2".
919
+ return bool(re.search(r"\bSources?\s+\d+", answer))
920
+
921
+
922
+ def markdown_bullets(sentences):
923
+ return "\n".join(f"* {sentence}" for sentence in sentences)
924
+
925
+
926
+ def build_relationship_answer(documents, question, source_id_by_key=None):
927
+ grouped_documents = group_documents_by_source(documents)
928
+ if len(grouped_documents) < 2:
929
+ return None
930
+ answer_parts = ["Based on the uploaded documents:"]
931
+ for source_name, source_documents in grouped_documents.items():
932
+ sentences = best_sentences_for_document(source_documents, question, max_sentences=2)
933
+ if sentences:
934
+ citation_suffix = citation_suffix_for_documents(source_documents, source_id_by_key)
935
+ answer_parts.append(f"* **{source_name}**{citation_suffix}: {' '.join(sentences)}")
936
+ source_list = ", ".join(grouped_documents.keys())
937
+ answer_parts.append(
938
+ f"\nTogether, these points show the relationship across {source_list} without using information outside the uploaded documents."
939
+ )
940
+ return "\n".join(answer_parts)
941
+
942
+
943
+ def build_comparison_answer(documents, question, source_id_by_key=None):
944
+ grouped_documents = group_documents_by_source(documents)
945
+ if len(grouped_documents) < 2:
946
+ return None
947
+ answer_parts = ["Based on the uploaded documents:"]
948
+ for source_name, source_documents in grouped_documents.items():
949
+ sentences = best_sentences_for_document(source_documents, question, max_sentences=2)
950
+ if sentences:
951
+ citation_suffix = citation_suffix_for_documents(source_documents, source_id_by_key)
952
+ answer_parts.append(f"* **{source_name}**{citation_suffix}: {' '.join(sentences)}")
953
+ answer_parts.append(
954
+ "\nIn comparison, each document describes a different role or focus, and the contrast above is limited to the retrieved PDF content."
955
+ )
956
+ return "\n".join(answer_parts)
957
+
958
+
959
+ def build_overview_answer(documents, question, source_id_by_key=None):
960
+ grouped_documents = group_documents_by_source(documents)
961
+ if not grouped_documents:
962
+ return None
963
+ answer_parts = ["The uploaded documents cover:"]
964
+ for source_name, source_documents in grouped_documents.items():
965
+ sentences = best_sentences_for_document(source_documents, question, max_sentences=2)
966
+ if sentences:
967
+ citation_suffix = citation_suffix_for_documents(source_documents, source_id_by_key)
968
+ answer_parts.append(f"* **{source_name}**{citation_suffix}: {' '.join(sentences)}")
969
+ return "\n".join(answer_parts)
970
+
971
+
972
+ def strip_trailing_question_punctuation(text):
973
+ end = len(text)
974
+ while end > 0 and text[end - 1] in "?.!":
975
+ end -= 1
976
+ return text[:end].strip()
977
+
978
+
979
+ def extract_factual_subject(question):
980
+ words = question.strip().split(maxsplit=2)
981
+ if len(words) < 3:
982
+ return None
983
+ prefix = (words[0].lower(), words[1].lower())
984
+ if prefix not in FACTUAL_QUESTION_PREFIXES:
985
+ return None
986
+ subject = strip_trailing_question_punctuation(words[2])
987
+ return subject or None
988
+
989
+
990
+ def build_factual_answer(documents, question, source_id_by_key=None):
991
+ if not has_grounded_keyword_overlap(question, documents):
992
+ return None
993
+ subject = extract_factual_subject(question)
994
+ keywords = query_keywords(subject or question)
995
+ grouped_documents = group_documents_by_source(documents)
996
+ supporting_sentences = []
997
+ for source_name, source_documents in grouped_documents.items():
998
+ sentences = best_sentences_for_document(source_documents, subject or question, max_sentences=2)
999
+ for sentence in sentences:
1000
+ if keywords and not keywords.intersection(tokenize_text(sentence)):
1001
+ continue
1002
+ supporting_sentences.append((source_name, sentence))
1003
+ if not supporting_sentences:
1004
+ return None
1005
+ source_name, first_sentence = supporting_sentences[0]
1006
+ citation_suffix = citation_suffix_for_documents(grouped_documents.get(source_name, []), source_id_by_key)
1007
+ if subject:
1008
+ if "document" in subject.lower() and "about" in subject.lower():
1009
+ answer = f"Based on **{source_name}**{citation_suffix}, {first_sentence}"
1010
+ else:
1011
+ answer = f"Based on **{source_name}**{citation_suffix}, {subject} is mentioned in this context: {first_sentence}"
1012
+ else:
1013
+ answer = f"Based on **{source_name}**{citation_suffix}, {first_sentence}"
1014
+ additional_sentences = [
1015
+ sentence
1016
+ for _source, sentence in supporting_sentences[1:3]
1017
+ if sentence.lower() != first_sentence.lower()
1018
+ ]
1019
+ if additional_sentences:
1020
+ answer += " " + " ".join(additional_sentences)
1021
+ return answer
1022
+
1023
+
1024
+ def build_answer_from_documents(question, documents, intent, source_id_by_key=None):
1025
+ if not has_grounded_keyword_overlap(question, documents) and intent != "overview":
1026
+ return INSUFFICIENT_CONTEXT_MESSAGE
1027
+ if intent == "relationship":
1028
+ return build_relationship_answer(documents, question, source_id_by_key=source_id_by_key) or INSUFFICIENT_CONTEXT_MESSAGE
1029
+ if intent == "comparison":
1030
+ return build_comparison_answer(documents, question, source_id_by_key=source_id_by_key) or INSUFFICIENT_CONTEXT_MESSAGE
1031
+ if intent == "overview":
1032
+ return build_overview_answer(documents, question, source_id_by_key=source_id_by_key) or INSUFFICIENT_CONTEXT_MESSAGE
1033
+ if intent == "factual":
1034
+ return build_factual_answer(documents, question, source_id_by_key=source_id_by_key) or INSUFFICIENT_CONTEXT_MESSAGE
1035
+ return INSUFFICIENT_CONTEXT_MESSAGE
1036
+
1037
+
1038
+ def _generate_followup_question(answer: str, question: str, docs: list) -> str:
1039
+ """Derive one non-yes/no follow-up from the answer text."""
1040
+ sentences = split_sentences(answer)
1041
+ base = sentences[0] if sentences else answer[:200]
1042
+
1043
+ prompt = (
1044
+ "Given this answer from a document: "
1045
+ f'"{base}" '
1046
+ "Write one thoughtful follow-up question (not yes/no) that would deepen "
1047
+ "understanding of the topic. Question only, no preamble:"
1048
+ )
1049
+ try:
1050
+ return generate_response(prompt, max_new_tokens=60).strip()
1051
+ except Exception:
1052
+ return "What further implications does this have for the broader topic?"
1053
+
1054
+
1055
+ def _generate_socratic_questions(question: str, docs: list) -> str:
1056
+ """Return 2-3 guiding questions without revealing the answer."""
1057
+ _SAFE_FALLBACK = (
1058
+ "🤔 Let's think through this together:\n\n"
1059
+ "1. What context does the document provide about this topic?\n"
1060
+ "2. What evidence does the document give that relates to your question?\n"
1061
+ "3. Based on that evidence, what conclusion can you draw?"
1062
+ )
1063
+ _INTERROGATIVES = {"what", "why", "how", "when", "where", "which", "who", "could", "can", "would", "is", "are", "do", "does"}
1064
+
1065
+ context_preview = " ".join(
1066
+ doc.page_content[:200] for doc in docs[:3]
1067
+ )
1068
+ prompt = (
1069
+ "You are a Socratic tutor. The student asked: "
1070
+ f'"{question}". '
1071
+ "Based on this document context (DO NOT reveal the answer): "
1072
+ f"{context_preview[:600]} "
1073
+ "Write 2-3 guiding questions that lead the student toward discovering "
1074
+ "the answer themselves. Go from broad to specific. Never state the answer:"
1075
+ )
1076
+ try:
1077
+ raw = generate_response(prompt, max_new_tokens=120).strip()
1078
+
1079
+ # Sanitize: keep only lines that look like genuine questions
1080
+ lines = [ln.strip() for ln in raw.splitlines()]
1081
+ question_lines = [
1082
+ ln for ln in lines
1083
+ if ln and (
1084
+ ln.endswith("?")
1085
+ or ln.split()[0].rstrip(".").lower() in _INTERROGATIVES
1086
+ )
1087
+ ]
1088
+
1089
+ # Enforce 2–3 questions; fall back if we can't satisfy the constraint
1090
+ if len(question_lines) < 2:
1091
+ return _SAFE_FALLBACK
1092
+ question_lines = question_lines[:3] # cap at 3
1093
+
1094
+ formatted = "\n".join(
1095
+ f"{i + 1}. {q}" for i, q in enumerate(question_lines)
1096
+ )
1097
+ return f"🤔 Let's think through this together:\n\n{formatted}"
1098
+ except Exception:
1099
+ return _SAFE_FALLBACK
1100
+
1101
+
1102
+ def _truncate_to_concise(answer: str, word_limit: int = 60) -> str:
1103
+ """Return first 1-2 sentences, hard-capped at word_limit words."""
1104
+ sentences = split_sentences(answer)
1105
+ if not sentences:
1106
+ return answer
1107
+ result = sentences[0]
1108
+ words = result.split()
1109
+ if len(words) > word_limit:
1110
+ result = " ".join(words[:word_limit]) + "…"
1111
+ return result
1112
+
1113
+
1114
+ def apply_mode_framing(
1115
+ answer: str,
1116
+ question: str,
1117
+ mode: str,
1118
+ docs: list,
1119
+ context: str,
1120
+ ) -> str:
1121
+ """Transform the grounded answer according to the requested mode."""
1122
+ if mode == "default" or not mode:
1123
+ return answer
1124
+
1125
+ if mode == "tutor":
1126
+ followup = _generate_followup_question(answer, question, docs)
1127
+ return f"{answer}\n\n---\n💡 To think about: {followup}"
1128
+
1129
+ if mode == "socratic":
1130
+ return _generate_socratic_questions(question, docs)
1131
+
1132
+ if mode == "eli5":
1133
+ prompt = (
1134
+ "Explain this simply. Use an analogy if helpful. "
1135
+ "Avoid technical jargon. Write short sentences. "
1136
+ "Assume the reader has no background in this topic. "
1137
+ "If a technical term is unavoidable, immediately explain it in "
1138
+ "plain language in parentheses. Use flowing prose, no bullet points.\n\n"
1139
+ f"Context:\n{context[:3000]}\n\n"
1140
+ f"Question: {question}\n"
1141
+ "Simple explanation:"
1142
+ )
1143
+ try:
1144
+ return generate_response(prompt, max_new_tokens=200).strip()
1145
+ except Exception:
1146
+ return answer
1147
+
1148
+ if mode == "concise":
1149
+ truncated = _truncate_to_concise(answer)
1150
+ if not truncated.strip():
1151
+ return "The document doesn't state this directly."
1152
+ return truncated
1153
+
1154
+ return answer
1155
+
1156
+
1157
+ def build_document_summary_bullets(documents, max_bullets=3):
1158
+ sentences = best_sentences_for_document(documents, max_sentences=max_bullets)
1159
+ if not sentences:
1160
+ return ["No readable summary content was found."]
1161
+ return sentences
1162
+
1163
+
1164
+ def shared_terms_between_documents(grouped_documents):
1165
+ document_term_sets = []
1166
+ for source_documents in grouped_documents.values():
1167
+ source_text = " ".join(document.page_content for document in source_documents)
1168
+ terms = {
1169
+ term
1170
+ for term in tokenize_text(source_text)
1171
+ if len(term) > 3 and term not in QUERY_STOPWORDS
1172
+ }
1173
+ if terms:
1174
+ document_term_sets.append(terms)
1175
+ if len(document_term_sets) < 2:
1176
+ return set()
1177
+ shared_terms = set.intersection(*document_term_sets)
1178
+ return shared_terms
1179
+
1180
+
1181
+ def build_combined_insights(grouped_documents):
1182
+ if len(grouped_documents) < 2:
1183
+ return []
1184
+ insights = []
1185
+ shared_terms = shared_terms_between_documents(grouped_documents)
1186
+ if shared_terms:
1187
+ shared_text = ", ".join(sorted(shared_terms)[:5])
1188
+ insights.append(f"Shared concepts across documents include {shared_text}.")
1189
+ source_descriptions = []
1190
+ for source_name, source_documents in grouped_documents.items():
1191
+ sentences = build_document_summary_bullets(source_documents, max_bullets=1)
1192
+ if sentences:
1193
+ source_descriptions.append(f"{source_name} focuses on {sentences[0]}")
1194
+ if source_descriptions:
1195
+ insights.append(" ".join(source_descriptions))
1196
+ if not insights:
1197
+ insights.append("The uploaded documents cover distinct but related areas of the session context.")
1198
+ return insights[:3]
1199
+
1200
+
1201
+ def build_session_summary(uploaded_documents, indexed_documents):
1202
+ document_summaries = []
1203
+ grouped_for_insights = {}
1204
+ for uploaded_document in uploaded_documents:
1205
+ document_chunks = documents_for_upload(indexed_documents, uploaded_document["document_id"])
1206
+ document_chunks = unique_documents(document_chunks)
1207
+ filename = uploaded_document["filename"]
1208
+ grouped_for_insights[filename] = document_chunks
1209
+ bullets = build_document_summary_bullets(document_chunks)
1210
+ document_summaries.append(f"## {filename}\n\n{markdown_bullets(bullets)}")
1211
+ combined_insights = build_combined_insights(grouped_for_insights)
1212
+ if combined_insights:
1213
+ document_summaries.append(f"## Combined Insights\n\n{markdown_bullets(combined_insights)}")
1214
+ return "\n\n".join(document_summaries)
1215
+
1216
+
1217
+ def representative_documents_by_source(documents, per_document_limit=2, max_documents=ASK_MAX_CONTEXT_CHUNKS):
1218
+ grouped_documents = group_documents_by_source(unique_documents(documents))
1219
+ representatives = []
1220
+ for source_documents in grouped_documents.values():
1221
+ representatives.extend(source_documents[:per_document_limit])
1222
+ if len(representatives) >= max_documents:
1223
+ break
1224
+ return representatives[:max_documents]
1225
+
1226
+
1227
+ def search_retrieval_candidates(vectorstore, question, candidate_count):
1228
+ try:
1229
+ scored_documents = vectorstore.similarity_search_with_score(question, k=candidate_count)
1230
+ return [
1231
+ (document, float(score), rank)
1232
+ for rank, (document, score) in enumerate(scored_documents)
1233
+ ]
1234
+ except Exception:
1235
+ logger.debug("Falling back to similarity_search without scores", exc_info=True)
1236
+ documents = vectorstore.similarity_search(question, k=candidate_count)
1237
+ return [
1238
+ (document, float(rank), rank)
1239
+ for rank, document in enumerate(documents)
1240
+ ]
1241
+
1242
+
1243
+ def dedupe_scored_candidates(scored_candidates):
1244
+ seen = set()
1245
+ unique_candidates = []
1246
+ for document, score, rank in scored_candidates:
1247
+ key = document_dedupe_key(document)
1248
+ if key in seen:
1249
+ continue
1250
+ seen.add(key)
1251
+ unique_candidates.append((document, score, rank))
1252
+ return unique_candidates
1253
+
1254
+
1255
+ def group_candidates_by_document(scored_candidates):
1256
+ grouped_candidates = {}
1257
+ document_order = []
1258
+ for document, score, rank in scored_candidates:
1259
+ document_id = document_identity(document)
1260
+ if document_id not in grouped_candidates:
1261
+ grouped_candidates[document_id] = []
1262
+ document_order.append(document_id)
1263
+ grouped_candidates[document_id].append((document, score, rank))
1264
+ return grouped_candidates, document_order
1265
+
1266
+
1267
+ def is_candidate_document_relevant(best_score, document_best_score, document_best_rank, document, keywords):
1268
+ if document_best_rank <= 1:
1269
+ return True
1270
+ if document_best_rank > ASK_DIVERSITY_RANK_LIMIT:
1271
+ return False
1272
+ score_cutoff = max(
1273
+ best_score + ASK_DIVERSITY_SCORE_MARGIN,
1274
+ best_score * ASK_DIVERSITY_SCORE_MULTIPLIER,
1275
+ )
1276
+ return (
1277
+ document_best_score <= score_cutoff
1278
+ or document_matches_query_terms(document, keywords)
1279
+ )
1280
+
1281
+
1282
+ def diversify_retrieved_documents(scored_candidates, question):
1283
+ unique_candidates = dedupe_scored_candidates(scored_candidates)
1284
+ if not unique_candidates:
1285
+ return []
1286
+ grouped_candidates, document_order = group_candidates_by_document(unique_candidates)
1287
+ best_score = unique_candidates[0][1]
1288
+ keywords = query_keywords(question)
1289
+ selected_candidates = []
1290
+ relevant_document_ids = []
1291
+ for document_id in document_order:
1292
+ document_best = grouped_candidates[document_id][0]
1293
+ if is_candidate_document_relevant(
1294
+ best_score, document_best[1], document_best[2], document_best[0], keywords,
1295
+ ):
1296
+ relevant_document_ids.append(document_id)
1297
+ per_document_limit = (
1298
+ ASK_MAX_CONTEXT_CHUNKS
1299
+ if len(relevant_document_ids) == 1
1300
+ else ASK_CHUNKS_PER_DOCUMENT
1301
+ )
1302
+ for document_id in relevant_document_ids:
1303
+ selected_candidates.extend(grouped_candidates[document_id][:per_document_limit])
1304
+ selected_keys = {
1305
+ document_dedupe_key(document)
1306
+ for document, _score, _rank in selected_candidates
1307
+ }
1308
+ for candidate in unique_candidates:
1309
+ document = candidate[0]
1310
+ document_id = document_identity(document)
1311
+ if len(selected_candidates) >= ASK_MAX_CONTEXT_CHUNKS:
1312
+ break
1313
+ if document_id not in relevant_document_ids:
1314
+ continue
1315
+ if document_dedupe_key(document) in selected_keys:
1316
+ continue
1317
+ selected_candidates.append(candidate)
1318
+ selected_keys.add(document_dedupe_key(document))
1319
+ selected_candidates.sort(key=lambda candidate: candidate[2])
1320
+ return [
1321
+ document for document, _score, _rank in selected_candidates[:ASK_MAX_CONTEXT_CHUNKS]
1322
+ ]
1323
+
1324
+
1325
+ def format_context(documents, max_chars=7000):
1326
+ context_parts = []
1327
+ remaining = max_chars
1328
+ for doc in documents:
1329
+ filename = document_display_name(doc)
1330
+ page = doc.metadata.get("page")
1331
+ source_label = f"{filename}, page {page + 1}" if isinstance(page, int) else filename
1332
+ # Pass 2b: prefer richer parent context for generation; fall back to page_content
1333
+ content = (doc.metadata.get("parent_chunk") or doc.page_content or "").strip()
1334
+ if not content:
1335
+ continue
1336
+ block = f"Document: {source_label}\nContent:\n{content}"
1337
+ if len(block) > remaining:
1338
+ block = block[:remaining].rsplit(" ", 1)[0]
1339
+ context_parts.append(block)
1340
+ remaining -= len(block)
1341
+ if remaining <= 0:
1342
+ break
1343
+ return "\n\n".join(context_parts)
1344
+
1345
+
1346
+ def citation_source_for_document(document, index):
1347
+ page = document.metadata.get("page")
1348
+ display_page = page + 1 if isinstance(page, int) else None
1349
+ text = concise_excerpt(document.page_content, 250)
1350
+
1351
+ return {
1352
+ "source_id": index + 1,
1353
+ "document": document_display_name(document) or "Unknown Document",
1354
+ "document_id": document.metadata.get("document_id"),
1355
+ "page": display_page,
1356
+ "text": text,
1357
+ "preview": concise_excerpt(document.page_content, 180),
1358
+ "chunk_index": document.metadata.get("chunk_index", index),
1359
+ }
1360
+
1361
+
1362
+ def collect_index_documents(vectorstore):
1363
+ docstore = getattr(vectorstore, "docstore", None)
1364
+ stored_docs = getattr(docstore, "_dict", {}) if docstore else {}
1365
+ return list(stored_docs.values())
1366
+
1367
+
1368
+ def documents_for_upload(all_documents, document_id):
1369
+ return [
1370
+ doc for doc in all_documents
1371
+ if doc.metadata.get("document_id") == document_id
1372
+ ]
1373
+
1374
+
1375
+ HF_GENERATION_MODEL = os.getenv("HF_GENERATION_MODEL", "google/flan-t5-base")
1376
+ generation_tokenizer = None
1377
+ generation_model = None
1378
+ generation_is_encoder_decoder = False
1379
+ embedding_model = None
1380
+
1381
+
1382
+ def get_embedding_model():
1383
+ global embedding_model
1384
+ if embedding_model is not None and hasattr(embedding_model, "embed_documents"):
1385
+ return embedding_model
1386
+
1387
+ with model_load_lock:
1388
+ if embedding_model is None or not hasattr(embedding_model, "embed_documents"):
1389
+ logger.info("Loading embedding model")
1390
+ loaded_embedding_model = HuggingFaceEmbeddings(
1391
+ model_name="sentence-transformers/all-MiniLM-L6-v2"
1392
+ )
1393
+ if loaded_embedding_model is None or not hasattr(loaded_embedding_model, "embed_documents"):
1394
+ raise RuntimeError("Embedding model failed to initialize.")
1395
+ embedding_model = loaded_embedding_model
1396
+ logger.info("Embedding model loaded successfully")
1397
+
1398
+ return embedding_model
1399
+
1400
+
1401
+ # ─────────────────────────────────────────────────────────────────────────────
1402
+ # Semantic Chunking Pipeline
1403
+ # ─────────────────────────────────────────────────────────────────────────────
1404
+
1405
+ # ── Cosine similarity (numpy, no extra deps) ──────────────────────────────────
1406
+
1407
+ def _cosine_similarity(vec_a: list, vec_b: list) -> float:
1408
+ """Cosine similarity between two embedding vectors; safe for zero norms."""
1409
+ a = np.array(vec_a, dtype=np.float32)
1410
+ b = np.array(vec_b, dtype=np.float32)
1411
+ norm_a = np.linalg.norm(a)
1412
+ norm_b = np.linalg.norm(b)
1413
+ if norm_a == 0.0 or norm_b == 0.0:
1414
+ return 0.0
1415
+ return float(np.dot(a, b) / (norm_a * norm_b))
1416
+
1417
+
1418
+ # ── Pass 1: boundary-aware splitting ─────────────────────────────────────────
1419
+
1420
+ _HEADING_RE = re.compile(
1421
+ r"(?m)"
1422
+ r"(?:^#{1,3} .+$"
1423
+ r"|.+:\s*$)"
1424
+ )
1425
+
1426
+
1427
+ def _split_pass1(text: str, soft_max: int) -> list:
1428
+ """
1429
+ Boundary-aware split in priority order:
1430
+ 1. Double-newline paragraph breaks
1431
+ 2. Markdown headings / lines ending in colon
1432
+ 3. Sentence terminals (. ? !)
1433
+ 4. Hard word-boundary split as last resort (never mid-word)
1434
+
1435
+ Returns a list of non-empty stripped strings.
1436
+ Crash-safe: empty or whitespace-only text returns [].
1437
+ """
1438
+ if not text or not text.strip():
1439
+ return []
1440
+
1441
+ paragraphs = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()]
1442
+
1443
+ chunks = []
1444
+ for para in paragraphs:
1445
+ if len(para) <= soft_max:
1446
+ if _HEADING_RE.match(para):
1447
+ chunks.append(para)
1448
+ else:
1449
+ if chunks and len(chunks[-1]) + len(para) + 1 <= soft_max:
1450
+ chunks[-1] = chunks[-1] + "\n" + para
1451
+ else:
1452
+ chunks.append(para)
1453
+ else:
1454
+ # Split large paragraph by heading boundaries first
1455
+ sub_parts = [s.strip() for s in _HEADING_RE.split(para) if s.strip()]
1456
+ for sub in sub_parts:
1457
+ if len(sub) <= soft_max:
1458
+ chunks.append(sub)
1459
+ else:
1460
+ # Sentence-level split
1461
+ sentences = re.split(r"(?<=[.?!])\s+", sub)
1462
+ current = ""
1463
+ for sent in sentences:
1464
+ sent = sent.strip()
1465
+ if not sent:
1466
+ continue
1467
+ candidate = (current + " " + sent).strip()
1468
+ if len(candidate) <= soft_max:
1469
+ current = candidate
1470
+ else:
1471
+ if current:
1472
+ chunks.append(current)
1473
+ if len(sent) > soft_max:
1474
+ # Hard word-boundary split — last resort
1475
+ while sent:
1476
+ piece = sent[:soft_max]
1477
+ # Back up to last space so we don't cut mid-word
1478
+ if len(sent) > soft_max and " " in piece:
1479
+ piece = piece.rsplit(" ", 1)[0]
1480
+ chunks.append(piece)
1481
+ sent = sent[len(piece):].lstrip()
1482
+ else:
1483
+ current = sent
1484
+ if current:
1485
+ chunks.append(current)
1486
+
1487
+ return [c for c in chunks if c.strip()]
1488
+
1489
+
1490
+ # ── Pass 2: semantic merge of tiny adjacent chunks ────────────────────────────
1491
+
1492
+ def _split_pass2(
1493
+ raw_chunks: list,
1494
+ threshold: float,
1495
+ merge_min: int,
1496
+ merge_max: int,
1497
+ ) -> list:
1498
+ """
1499
+ Merge adjacent tiny chunks (< merge_min chars) when:
1500
+ - cosine similarity >= threshold, AND
1501
+ - merged length <= merge_max
1502
+
1503
+ Only tiny chunks and their immediate neighbours are embedded,
1504
+ keeping latency proportional to fragment count, not total chunks.
1505
+ """
1506
+ if not raw_chunks:
1507
+ return []
1508
+
1509
+ tiny_indices = [i for i, c in enumerate(raw_chunks) if len(c) < merge_min]
1510
+ if not tiny_indices:
1511
+ return list(raw_chunks) # fast-path: nothing to merge
1512
+
1513
+ # Collect tiny chunks + their immediate neighbours for batch embedding
1514
+ neighbour_indices = set()
1515
+ for idx in tiny_indices:
1516
+ neighbour_indices.add(idx)
1517
+ if idx > 0:
1518
+ neighbour_indices.add(idx - 1)
1519
+ if idx < len(raw_chunks) - 1:
1520
+ neighbour_indices.add(idx + 1)
1521
+
1522
+ sorted_indices = sorted(neighbour_indices)
1523
+ texts_to_embed = [raw_chunks[i] for i in sorted_indices]
1524
+
1525
+ try:
1526
+ emb_model = get_embedding_model()
1527
+ embeddings_list = emb_model.embed_documents(texts_to_embed)
1528
+ except Exception:
1529
+ logger.warning("Semantic merge embedding failed — skipping merge pass", exc_info=True)
1530
+ return list(raw_chunks)
1531
+
1532
+ emb_map = {idx: emb for idx, emb in zip(sorted_indices, embeddings_list)}
1533
+
1534
+ result = []
1535
+ i = 0
1536
+ while i < len(raw_chunks):
1537
+ chunk = raw_chunks[i]
1538
+ if len(chunk) >= merge_min:
1539
+ result.append(chunk)
1540
+ i += 1
1541
+ continue
1542
+
1543
+ # Try to merge with next chunk
1544
+ if i + 1 < len(raw_chunks):
1545
+ next_chunk = raw_chunks[i + 1]
1546
+ merged_len = len(chunk) + len(next_chunk) + 1
1547
+ emb_a = emb_map.get(i)
1548
+ emb_b = emb_map.get(i + 1)
1549
+ if (
1550
+ emb_a is not None
1551
+ and emb_b is not None
1552
+ and merged_len <= merge_max
1553
+ and _cosine_similarity(emb_a, emb_b) >= threshold
1554
+ ):
1555
+ result.append((chunk + " " + next_chunk).strip())
1556
+ i += 2
1557
+ continue
1558
+
1559
+ # Try to append to previous chunk
1560
+ if result:
1561
+ prev = result[-1]
1562
+ merged_len = len(prev) + len(chunk) + 1
1563
+ emb_a = emb_map.get(i - 1)
1564
+ emb_b = emb_map.get(i)
1565
+ if (
1566
+ emb_a is not None
1567
+ and emb_b is not None
1568
+ and merged_len <= merge_max
1569
+ and _cosine_similarity(emb_a, emb_b) >= threshold
1570
+ ):
1571
+ result[-1] = (prev + " " + chunk).strip()
1572
+ i += 1
1573
+ continue
1574
+
1575
+ # Cannot merge — keep as orphan
1576
+ result.append(chunk)
1577
+ i += 1
1578
+
1579
+ return [c for c in result if c.strip()]
1580
+
1581
+
1582
+ # ── Pass 2b: parent context window ───────────────────────────────────────────
1583
+
1584
+ def _build_parent_context(chunks: list, idx: int, window: int = 1) -> str:
1585
+ """Return chunk at idx plus up to `window` neighbours on each side."""
1586
+ start = max(0, idx - window)
1587
+ end = min(len(chunks), idx + window + 1)
1588
+ return " ".join(chunks[start:end]).strip()
1589
+
1590
+
1591
+ # ── Public entry point ────────────────────────────────────────────────────────
1592
+
1593
+ def semantic_chunk(text: str, filename: str, page_number: int, document_id: str) -> list:
1594
+ """
1595
+ Two-pass semantic chunker returning LangChain Document objects.
1596
+
1597
+ Pass 1 — boundary-aware split (paragraph > heading > sentence > hard).
1598
+ Pass 2 — merge adjacent tiny chunks by embedding cosine similarity.
1599
+ Pass 2b — attach small_chunk + parent_chunk to each Document's metadata.
1600
+
1601
+ Guaranteed crash-safe for empty / single-sentence pages (returns []).
1602
+ Metadata keys: document_id, filename, page, chunk_index,
1603
+ small_chunk (Pass 2b), parent_chunk (Pass 2b).
1604
+ """
1605
+ if not text or not text.strip():
1606
+ logger.debug(
1607
+ "semantic_chunk: empty text filename=%s page=%s — skipping",
1608
+ filename, page_number,
1609
+ )
1610
+ return []
1611
+
1612
+ # Pass 1
1613
+ raw_chunks = _split_pass1(text, soft_max=SEMANTIC_CHUNK_SOFT_MAX)
1614
+ if not raw_chunks:
1615
+ return []
1616
+
1617
+ # Pass 2
1618
+ merge_start = time.time()
1619
+ merged_chunks = _split_pass2(
1620
+ raw_chunks,
1621
+ threshold=SEMANTIC_CHUNK_SIMILARITY_THRESHOLD,
1622
+ merge_min=SEMANTIC_CHUNK_MERGE_MIN,
1623
+ merge_max=SEMANTIC_CHUNK_MERGE_MAX,
1624
+ )
1625
+ merge_elapsed = time.time() - merge_start
1626
+ if merge_elapsed > SEMANTIC_CHUNK_MERGE_WARN_SECS:
1627
+ logger.warning(
1628
+ "Semantic merge took %.2fs (> %.1fs) filename=%s page=%s chunks=%s",
1629
+ merge_elapsed,
1630
+ SEMANTIC_CHUNK_MERGE_WARN_SECS,
1631
+ filename,
1632
+ page_number,
1633
+ len(merged_chunks),
1634
+ )
1635
+
1636
+ # Pass 2b + Document construction
1637
+ try:
1638
+ from langchain_core.documents import Document as _Doc
1639
+ except Exception:
1640
+ from langchain.schema import Document as _Doc # type: ignore
1641
+
1642
+ documents = []
1643
+ for idx, chunk_text in enumerate(merged_chunks):
1644
+ if not chunk_text.strip():
1645
+ continue
1646
+ meta = {
1647
+ "document_id": document_id,
1648
+ "filename": filename,
1649
+ "page": page_number,
1650
+ "chunk_index": idx,
1651
+ }
1652
+ if SEMANTIC_CHUNK_HIERARCHICAL:
1653
+ meta["small_chunk"] = chunk_text
1654
+ meta["parent_chunk"] = _build_parent_context(merged_chunks, idx)
1655
+ documents.append(_Doc(page_content=chunk_text, metadata=meta))
1656
+
1657
+ return documents
1658
+
1659
+
1660
+ def load_generation_model():
1661
+ global generation_tokenizer, generation_model, generation_is_encoder_decoder
1662
+ if generation_model is not None and generation_tokenizer is not None:
1663
+ return generation_tokenizer, generation_model, generation_is_encoder_decoder
1664
+
1665
+ logger.info("Acquiring model load lock")
1666
+
1667
+ with model_load_lock:
1668
+ if generation_model is not None and generation_tokenizer is not None:
1669
+ return generation_tokenizer, generation_model, generation_is_encoder_decoder
1670
+
1671
+ logger.info(
1672
+ "Loading generation model model=%s",
1673
+ HF_GENERATION_MODEL,
1674
+ )
1675
+
1676
+ config = AutoConfig.from_pretrained(HF_GENERATION_MODEL)
1677
+ generation_is_encoder_decoder = bool(getattr(config, "is_encoder_decoder", False))
1678
+ generation_tokenizer = AutoTokenizer.from_pretrained(HF_GENERATION_MODEL)
1679
+
1680
+ if generation_is_encoder_decoder:
1681
+ generation_model = AutoModelForSeq2SeqLM.from_pretrained(HF_GENERATION_MODEL)
1682
+ else:
1683
+ generation_model = AutoModelForCausalLM.from_pretrained(HF_GENERATION_MODEL)
1684
+
1685
+ if torch.cuda.is_available():
1686
+ generation_model = generation_model.to("cuda")
1687
+
1688
+ generation_model.eval()
1689
+ logger.info("Generation model loaded successfully")
1690
+
1691
+ return generation_tokenizer, generation_model, generation_is_encoder_decoder
1692
+
1693
+
1694
+ def generate_response(prompt: str, max_new_tokens: int) -> str:
1695
+ tokenizer, model, is_encoder_decoder = load_generation_model()
1696
+ model_device = next(model.parameters()).device
1697
+
1698
+ # Tokenize and move to device before acquiring the lock so
1699
+ # CPU-bound preprocessing does not block other threads unnecessarily.
1700
+ encoded = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
1701
+ encoded = {key: value.to(model_device) for key, value in encoded.items()}
1702
+ pad_token_id = (
1703
+ tokenizer.pad_token_id
1704
+ if tokenizer.pad_token_id is not None
1705
+ else tokenizer.eos_token_id
1706
+ )
1707
+
1708
+ # Only the model.generate() call is locked — tokenization and device
1709
+ # transfer above happen in parallel across threads. The lock purely
1710
+ # serialises the GPU/CPU forward pass itself which is not thread-safe.
1711
+ logger.debug("Acquiring generation lock")
1712
+ with generation_lock:
1713
+ with torch.no_grad():
1714
+ generated_ids = model.generate(
1715
+ **encoded,
1716
+ max_new_tokens=max_new_tokens,
1717
+ do_sample=False,
1718
+ pad_token_id=pad_token_id,
1719
+ )
1720
+ logger.debug("Generation completed")
1721
+
1722
+ if is_encoder_decoder:
1723
+ text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
1724
+ return text.strip()
1725
+ input_len = encoded["input_ids"].shape[1]
1726
+ new_tokens = generated_ids[0][input_len:]
1727
+ text = tokenizer.decode(new_tokens, skip_special_tokens=True)
1728
+ return text.strip()
1729
+
1730
+
1731
+ def sanitize_upload_filename(client_file_path: str) -> str:
1732
+ if not client_file_path or not client_file_path.strip():
1733
+ raise ValueError("Missing PDF file path.")
1734
+ stripped_path = client_file_path.strip()
1735
+ normalized_path = stripped_path.replace("\\", "/")
1736
+ safe_name = normalized_path.rsplit("/", 1)[-1].strip()
1737
+ if not safe_name:
1738
+ raise ValueError("Missing PDF file path.")
1739
+ if safe_name in {".", ".."} or ".." in safe_name:
1740
+ raise ValueError("Invalid upload filename.")
1741
+ if "/" in safe_name or "\\" in safe_name:
1742
+ raise ValueError("Invalid upload filename.")
1743
+ if any(character not in UPLOAD_FILENAME_CHARS for character in safe_name):
1744
+ raise ValueError("Uploaded filename contains unsupported characters.")
1745
+ if not safe_name.lower().endswith(".pdf"):
1746
+ raise ValueError("Only PDF files are allowed.")
1747
+ return safe_name
1748
+
1749
+
1750
+ def get_trusted_upload_path(file_name: str) -> str:
1751
+ trusted_path = os.path.join(str(UPLOADS_DIR), file_name)
1752
+ normalized_uploads_dir = os.path.abspath(str(UPLOADS_DIR))
1753
+ normalized_path = os.path.abspath(trusted_path)
1754
+ if os.path.dirname(normalized_path) != normalized_uploads_dir:
1755
+ raise ValueError("Invalid upload path.")
1756
+ return normalized_path
1757
+
1758
+
1759
+ def validate_uploaded_pdf(file_path: str) -> str:
1760
+ trusted_path = os.fspath(file_path)
1761
+ if not trusted_path.lower().endswith(".pdf"):
1762
+ raise ValueError("Only PDF files are allowed.")
1763
+ # CodeQL [py/path-injection]: trusted server-constructed upload path
1764
+ if not os.path.isfile(trusted_path):
1765
+ raise ValueError("File does not exist or is not a valid file.")
1766
+ # CodeQL [py/path-injection]: trusted server-constructed upload path
1767
+ if os.path.getsize(trusted_path) == 0:
1768
+ raise ValueError("Uploaded PDF is empty. Please choose a valid PDF file.")
1769
+ return trusted_path
1770
+
1771
+
1772
+ VALID_MODES = {"default", "tutor", "socratic", "eli5", "concise"}
1773
+
1774
+ class Question(BaseModel):
1775
+ question: str = Field(..., min_length=1, description="Question cannot be empty")
1776
+ session_id: UUID
1777
+ mode: str = Field(default="default")
1778
+ session_secret: str | None = None
1779
+
1780
+ @field_validator("question")
1781
+ @classmethod
1782
+ def question_must_not_be_blank(cls, v: str) -> str:
1783
+ if not v.strip():
1784
+ raise ValueError("Question cannot be whitespace only")
1785
+ return v
1786
+
1787
+ @field_validator("mode")
1788
+ @classmethod
1789
+ def validate_mode(cls, v: str) -> str:
1790
+ normalized = v.strip().lower()
1791
+ if normalized not in VALID_MODES:
1792
+ raise ValueError(f"Invalid mode '{v}'. Must be one of {VALID_MODES}")
1793
+ return normalized
1794
+
1795
+
1796
+ class SummarizeRequest(BaseModel):
1797
+ pdf: str | None = None
1798
+ session_id: UUID
1799
+
1800
+ session_secret: str | None = None
1801
+
1802
+
1803
+ class SessionLookupItem(BaseModel):
1804
+ session_id: UUID
1805
+ session_secret: str = Field(..., min_length=1)
1806
+
1807
+
1808
+ class SessionsLookupRequest(BaseModel):
1809
+ sessions: list[SessionLookupItem] = Field(..., min_length=1, max_length=50)
1810
+
1811
+ @app.get("/sessions")
1812
+ def get_sessions():
1813
+ raise HTTPException(
1814
+ status_code=410,
1815
+ detail="Endpoint removed. Use /sessions/lookup with session_id + session_secret.",
1816
+ )
1817
+
1818
+
1819
+ def _require_session_secret(session: dict, provided_secret: str | None):
1820
+ candidate = (provided_secret or "").strip()
1821
+ if not candidate:
1822
+ raise HTTPException(status_code=403, detail="Forbidden")
1823
+
1824
+ expected = (session.get("session_secret") or "").strip()
1825
+ if not expected or not secrets.compare_digest(candidate, expected):
1826
+ raise HTTPException(status_code=403, detail="Forbidden")
1827
+
1828
+
1829
+ @app.post("/sessions/lookup")
1830
+ def lookup_sessions(data: SessionsLookupRequest):
1831
+ cleanup_expired_sessions()
1832
+
1833
+ sessions_out = []
1834
+
1835
+ with sessions_lock:
1836
+ for item in data.sessions:
1837
+ sid = str(item.session_id)
1838
+ session = _touch_session_unlocked(sid)
1839
+ if not session:
1840
+ continue
1841
+
1842
+ _require_session_secret(session, item.session_secret)
1843
+
1844
+ sessions_out.append(
1845
+ {
1846
+ "session_id": sid,
1847
+ "created_at": session.get("created_at"),
1848
+ "last_accessed": session.get("last_accessed"),
1849
+ "documents": session.get("documents", []),
1850
+ "chat": session.get("chat", []),
1851
+ }
1852
+ )
1853
+
1854
+ return sessions_out
1855
+
1856
+ class SessionWriteRequest(BaseModel):
1857
+ session_id: UUID
1858
+ session_secret: str
1859
+
1860
+
1861
+ @app.post("/process-pdf")
1862
+ def process_pdf(
1863
+ file: UploadFile = File(...),
1864
+ session_id: str | None = Form(None),
1865
+ original_filename: str | None = Form(None),
1866
+ session_secret: str | None = Form(None)
1867
+ ):
1868
+ cleanup_expired_sessions()
1869
+
1870
+ # If original_filename is provided, use it for display, otherwise fallback to the file's name (which might be a UUID)
1871
+ filename = original_filename or file.filename or "uploaded.pdf"
1872
+ if not filename.lower().endswith(".pdf"):
1873
+ raise HTTPException(status_code=400, detail="Only PDF documents are supported.")
1874
+ requested_session_id = None
1875
+ if session_id:
1876
+ try:
1877
+ requested_session_id = normalize_session_id(session_id)
1878
+ except ValueError:
1879
+ raise HTTPException(status_code=400, detail="Invalid session ID format.")
1880
+ requested_session_secret = (session_secret or "").strip() or None
1881
+
1882
+ logger.info(
1883
+ "Processing PDF filename=%s existing_session=%s",
1884
+ filename,
1885
+ bool(requested_session_id),
1886
+ )
1887
+
1888
+ os.makedirs(str(UPLOADS_DIR), exist_ok=True)
1889
+ temp_filename = f"temp_{uuid.uuid4().hex}.pdf"
1890
+ temp_path = os.path.join(str(UPLOADS_DIR), temp_filename)
1891
+
1892
+ try:
1893
+ # Validate actual file magic bytes — extension alone is trivially bypassable.
1894
+ # A valid PDF always begins with the 4-byte signature: %PDF (0x25 0x50 0x44 0x46).
1895
+ magic = file.file.read(5)
1896
+ if magic[:4] != b"%PDF":
1897
+ raise HTTPException(
1898
+ status_code=415,
1899
+ detail="Invalid file type. Only real PDF documents are accepted."
1900
+ )
1901
+ file.file.seek(0) # Reset stream so we can copy the full file
1902
+
1903
+ max_size = 20 * 1024 * 1024
1904
+ bytes_written = 0
1905
+ with open(temp_path, "wb") as f:
1906
+ while chunk := file.file.read(65536):
1907
+ bytes_written += len(chunk)
1908
+ if bytes_written > max_size:
1909
+ raise HTTPException(status_code=413, detail="Uploaded PDF exceeds the maximum size of 20MB.")
1910
+ f.write(chunk)
1911
+
1912
+ if bytes_written == 0:
1913
+ raise HTTPException(status_code=400, detail="Uploaded PDF is empty. Please choose a valid PDF file.")
1914
+
1915
+ try:
1916
+ docs = extract_pdf_documents_sandboxed(temp_path, filename)
1917
+ except Exception as exc:
1918
+ logger.warning("Failed to load PDF filename=%s error=%s", filename, exc)
1919
+ if isinstance(exc, HTTPException):
1920
+ raise
1921
+ raise HTTPException(status_code=400, detail="Unable to read this PDF. It may be corrupted or encrypted.")
1922
+ finally:
1923
+ file.file.close()
1924
+ if os.path.exists(temp_path):
1925
+ try:
1926
+ os.remove(temp_path)
1927
+ except Exception as e:
1928
+ logger.error("Failed to delete temp file %s: %s", temp_path, e)
1929
+
1930
+ if not docs:
1931
+ raise HTTPException(status_code=400, detail="No readable pages were found in the PDF.")
1932
+
1933
+ # ── Semantic chunking (Pass 1 + Pass 2 + Pass 2b) ────────────────────────
1934
+ # document_id is generated here so it can be embedded in chunk metadata
1935
+ # at construction time, avoiding a second metadata-overwrite loop.
1936
+ document_id = str(uuid.uuid4())
1937
+
1938
+ all_chunks = []
1939
+ seen_content = set()
1940
+ for doc in docs:
1941
+ page_number = doc.metadata.get("page", 0)
1942
+ page_text = doc.page_content or ""
1943
+ for chunk_doc in semantic_chunk(page_text, filename, page_number, document_id):
1944
+ content = chunk_doc.page_content.strip()
1945
+ if content and content not in seen_content:
1946
+ seen_content.add(content)
1947
+ all_chunks.append(chunk_doc)
1948
+ chunks = all_chunks
1949
+
1950
+ if not chunks:
1951
+ raise HTTPException(status_code=400, detail="No text chunks generated from the PDF. Please check your file.")
1952
+ if not requested_session_id and len(chunks) > MAX_CHUNKS_PER_SESSION:
1953
+ raise HTTPException(
1954
+ status_code=400,
1955
+ detail=(
1956
+ f"PDF is too large to index. "
1957
+ f"A single document may not exceed {MAX_CHUNKS_PER_SESSION} chunks."
1958
+ ),
1959
+ )
1960
+ if requested_session_id:
1961
+ with session_store_lock(requested_session_id):
1962
+ with sessions_lock:
1963
+ session = _peek_session_unlocked(requested_session_id)
1964
+ if not session:
1965
+ raise HTTPException(status_code=404, detail="Session expired or invalid. Please re-upload your PDFs.")
1966
+ expected_secret = (session.get("session_secret") or "").strip()
1967
+ if not expected_secret or not requested_session_secret or not secrets.compare_digest(requested_session_secret, expected_secret):
1968
+ raise HTTPException(status_code=403, detail="Forbidden")
1969
+ if len(session.get("documents", [])) >= MAX_DOCUMENTS_PER_SESSION:
1970
+ raise HTTPException(status_code=400, detail="Maximum number of documents per session reached.")
1971
+ current_chunks = sum(doc.get("chunk_count", 0) for doc in session.get("documents", []))
1972
+ if current_chunks + len(chunks) > MAX_CHUNKS_PER_SESSION:
1973
+ raise HTTPException(status_code=400, detail="Maximum number of chunks per session exceeded.")
1974
+ elif len(chunks) > MAX_CHUNKS_PER_SESSION:
1975
+ raise HTTPException(
1976
+ status_code=400,
1977
+ detail=f"PDF is too large to index. A single document may not exceed {MAX_CHUNKS_PER_SESSION} chunks.",
1978
+ )
1979
+
1980
+ document_id = str(uuid.uuid4())
1981
+ processing_session_id = requested_session_id
1982
+ created_placeholder_session = False
1983
+
1984
+ if not processing_session_id:
1985
+ processing_session_id = str(uuid.uuid4())
1986
+ created_placeholder_session = True
1987
+ created_at = now_ts()
1988
+ new_session_secret = generate_session_secret()
1989
+ with sessions_lock:
1990
+ _cleanup_expired_sessions_unlocked()
1991
+ _enforce_max_sessions_unlocked()
1992
+ sessions[processing_session_id] = {
1993
+ "vectorstore": None,
1994
+ "lock": threading.Lock(),
1995
+ "documents": [],
1996
+ "session_secret": new_session_secret,
1997
+ "session_dir": None,
1998
+ "created_at": created_at,
1999
+ "last_accessed": created_at,
2000
+ "retrieval_cache": {},
2001
+ "chat": [],
2002
+ }
2003
+ persist_session_registry_entry(processing_session_id, sessions[processing_session_id])
2004
+
2005
+ update_processing_progress(processing_session_id, "Starting", 5)
2006
+
2007
+ update_processing_progress(
2008
+ processing_session_id,
2009
+ "Extracting text from PDF",
2010
+ 15
2011
+ )
2012
+ now = now_ts()
2013
+ uploaded_document = {
2014
+ "document_id": document_id,
2015
+ "filename": filename,
2016
+ "static_url": f"/uploads/{os.path.basename(file.filename)}" if file.filename else None,
2017
+ "uploaded_at": now,
2018
+ "chunk_count": len(chunks),
2019
+ }
2020
+
2021
+ # Stamp uploaded_at only — document_id, filename, page, chunk_index are
2022
+ # already set by semantic_chunk() at construction time.
2023
+ for chunk in chunks:
2024
+ chunk.metadata["uploaded_at"] = now
2025
+
2026
+ try:
2027
+ embeddings = get_embedding_model()
2028
+ except Exception:
2029
+ logger.exception("Failed to load embedding model filename=%s", filename)
2030
+ raise HTTPException(
2031
+ status_code=503,
2032
+ detail=(
2033
+ "Embedding model is unavailable. Start the RAG service once with internet access "
2034
+ "to download sentence-transformers/all-MiniLM-L6-v2, or pre-download it into the "
2035
+ "local Hugging Face cache."
2036
+ ),
2037
+ )
2038
+
2039
+ try:
2040
+ new_vectorstore = FAISS.from_documents(chunks, embeddings)
2041
+ except Exception as exc:
2042
+ logger.exception("Failed to create vectorstore filename=%s", filename)
2043
+ raise HTTPException(status_code=500, detail="Failed to index the uploaded PDF.")
2044
+
2045
+ if requested_session_id:
2046
+ with session_store_lock(requested_session_id):
2047
+ with sessions_lock:
2048
+ session = _touch_session_unlocked(requested_session_id)
2049
+ if not session:
2050
+ raise HTTPException(status_code=404, detail="Session expired or invalid. Please re-upload your PDFs.")
2051
+ session.setdefault("retrieval_cache", {})
2052
+ if "lock" not in session:
2053
+ session["lock"] = threading.Lock()
2054
+ session_lock = session["lock"]
2055
+ vectorstore = session["vectorstore"]
2056
+
2057
+ with session_lock:
2058
+ try:
2059
+ vectorstore.merge_from(new_vectorstore)
2060
+ persist_vectorstore(requested_session_id, vectorstore)
2061
+ except Exception:
2062
+ logger.exception(
2063
+ "Failed to merge vectorstore session_id=%s filename=%s",
2064
+ requested_session_id,
2065
+ filename,
2066
+ )
2067
+ raise HTTPException(status_code=500, detail="Failed to merge the uploaded PDF into this session.")
2068
+
2069
+ with sessions_lock:
2070
+ session = _touch_session_unlocked(requested_session_id)
2071
+ if not session:
2072
+ raise HTTPException(status_code=404, detail="Session expired or invalid. Please re-upload your PDFs.")
2073
+ session.setdefault("documents", []).append(uploaded_document)
2074
+ session["last_accessed"] = now
2075
+ session["retrieval_cache"] = {}
2076
+ session_id = requested_session_id
2077
+ persist_session_registry_entry(session_id, session)
2078
+ logger.info(
2079
+ "Merged PDF into session session_id=%s filename=%s documents=%s chunks=%s",
2080
+ session_id,
2081
+ filename,
2082
+ len(session["documents"]),
2083
+ len(chunks),
2084
+ )
2085
+ else:
2086
+ with session_store_lock(session_id := str(uuid.uuid4())):
2087
+ session_secret = generate_session_secret()
2088
+ session_dir = persist_vectorstore(session_id, new_vectorstore)
2089
+
2090
+ with sessions_lock:
2091
+ _cleanup_expired_sessions_unlocked()
2092
+ _enforce_max_sessions_unlocked()
2093
+ if processing_session_id in processing_progress:
2094
+ processing_progress[session_id] = processing_progress.pop(processing_session_id)
2095
+ processing_session_id = session_id
2096
+ session_lock = threading.Lock()
2097
+ sessions[session_id] = {
2098
+ "vectorstore": new_vectorstore,
2099
+ "lock": session_lock,
2100
+ "documents": [uploaded_document],
2101
+ "session_secret": session_secret,
2102
+ "session_dir": session_dir,
2103
+ "created_at": now,
2104
+ "last_accessed": now,
2105
+ "retrieval_cache": {},
2106
+ "chat": [],
2107
+ }
2108
+ persist_session_registry_entry(session_id, sessions[session_id])
2109
+ logger.info(
2110
+ "Created session session_id=%s filename=%s chunks=%s",
2111
+ session_id,
2112
+ filename,
2113
+ len(chunks),
2114
+ )
2115
+
2116
+
2117
+ with sessions_lock:
2118
+ documents = list(sessions[session_id].get("documents", []))
2119
+ update_processing_progress(
2120
+ session_id,
2121
+ "Completed",
2122
+ 100
2123
+ )
2124
+ return {
2125
+ "message": "PDF processed successfully",
2126
+ "session_id": session_id,
2127
+ "session_secret": sessions[session_id].get("session_secret"),
2128
+ "document": uploaded_document,
2129
+ "documents": documents,
2130
+ }
2131
+
2132
+
2133
+ @app.post("/validate-session-write")
2134
+ def validate_session_write(data: SessionWriteRequest):
2135
+ session_id = str(data.session_id)
2136
+ provided_secret = (data.session_secret or "").strip()
2137
+
2138
+ if not provided_secret:
2139
+ raise HTTPException(status_code=403, detail="Forbidden")
2140
+
2141
+ with session_store_lock(session_id):
2142
+ with sessions_lock:
2143
+ session = _peek_session_unlocked(session_id)
2144
+ if not session:
2145
+ raise HTTPException(status_code=404, detail="Session expired or invalid. Please re-upload your PDFs.")
2146
+
2147
+ expected_secret = (session.get("session_secret") or "").strip()
2148
+ if not expected_secret or not secrets.compare_digest(provided_secret, expected_secret):
2149
+ raise HTTPException(status_code=403, detail="Forbidden")
2150
+
2151
+ return {"allowed": True}
2152
+
2153
+
2154
+
2155
+
2156
+ @app.get("/processing-status/{session_id}")
2157
+ def processing_status(session_id: str, session_secret: str | None = None):
2158
+
2159
+ with sessions_lock:
2160
+ meta = _touch_session_unlocked(session_id)
2161
+ if meta:
2162
+ _require_session_secret(meta, session_secret)
2163
+ progress = meta.get("processing_progress") if meta else None
2164
+
2165
+ if not progress:
2166
+ raise HTTPException(
2167
+ status_code=404,
2168
+ detail="No processing status found."
2169
+ )
2170
+
2171
+ return progress
2172
+
2173
+
2174
+ @app.post("/ask")
2175
+ def ask_question(data: Question):
2176
+ cleanup_expired_sessions()
2177
+
2178
+ question = (data.question or "").strip()
2179
+
2180
+ if not question:
2181
+ raise HTTPException(
2182
+ status_code=400,
2183
+ detail="Question is required."
2184
+ )
2185
+
2186
+ intent = detect_question_intent(question)
2187
+ session_id = str(data.session_id)
2188
+ mode = data.mode
2189
+
2190
+ # Normalize query for cache reuse
2191
+ normalized_query = normalize_query(question)
2192
+
2193
+
2194
+ with sessions_lock:
2195
+
2196
+ session = _touch_session_unlocked(session_id)
2197
+
2198
+ if not session:
2199
+ raise HTTPException(
2200
+ status_code=404,
2201
+ detail="Session expired or invalid. Please re-upload your PDFs."
2202
+ )
2203
+
2204
+ _require_session_secret(session, data.session_secret)
2205
+
2206
+ if "lock" not in session:
2207
+ session["lock"] = threading.Lock()
2208
+
2209
+ session_lock = session["lock"]
2210
+ if not session.get("vectorstore"):
2211
+ try:
2212
+ session["vectorstore"] = FAISS.load_local(str(FAISS_DIR / session_id), embedding_model, allow_dangerous_deserialization=True)
2213
+ except Exception as e:
2214
+ logger.error(f"Failed to lazy load vectorstore: {e}")
2215
+ raise HTTPException(status_code=500, detail="Failed to load session index.")
2216
+ vectorstore = session["vectorstore"]
2217
+
2218
+ # Session-level retrieval cache
2219
+ retrieval_cache = session.setdefault(
2220
+ "retrieval_cache",
2221
+ {}
2222
+ )
2223
+
2224
+ # Cache hit
2225
+ cache_key = f"{mode}:{normalized_query}"
2226
+ if cache_key in retrieval_cache:
2227
+
2228
+ logger.info(
2229
+ "Retrieval cache hit session_id=%s cache_key=%s",
2230
+ session_id,
2231
+ cache_key,
2232
+ )
2233
+
2234
+ scored_candidates = retrieval_cache[
2235
+ cache_key
2236
+ ]
2237
+
2238
+ cache_hit = True
2239
+
2240
+ else:
2241
+ cache_hit = False
2242
+
2243
+ try:
2244
+ with session_lock:
2245
+ indexed_documents = collect_index_documents(vectorstore)
2246
+
2247
+ if not cache_hit:
2248
+ logger.info(
2249
+ "Retrieval cache miss session_id=%s cache_key=%s",
2250
+ session_id,
2251
+ cache_key,
2252
+ )
2253
+ scored_candidates = search_retrieval_candidates(
2254
+ vectorstore,
2255
+ question,
2256
+ ASK_RETRIEVAL_CANDIDATES,
2257
+ )
2258
+
2259
+ with sessions_lock:
2260
+ session = sessions.get(session_id)
2261
+ if session:
2262
+ retrieval_cache = session.setdefault("retrieval_cache", {})
2263
+ if len(retrieval_cache) >= RETRIEVAL_CACHE_LIMIT:
2264
+ oldest_key = next(iter(retrieval_cache))
2265
+ del retrieval_cache[oldest_key]
2266
+ retrieval_cache[cache_key] = scored_candidates
2267
+
2268
+ except Exception:
2269
+ logger.exception("Similarity search failed session_id=%s", session_id)
2270
+ raise HTTPException(status_code=500, detail="Failed to search the uploaded documents.")
2271
+
2272
+ docs = (
2273
+ representative_documents_by_source(indexed_documents)
2274
+ if intent == "overview"
2275
+ else diversify_retrieved_documents(
2276
+ scored_candidates,
2277
+ question
2278
+ )
2279
+ )
2280
+
2281
+ best_score = scored_candidates[0][1] if scored_candidates else None
2282
+ if not passes_evidence_gate(question, docs, best_score, intent):
2283
+ logger.info(
2284
+ "Evidence gate refused answer session_id=%s intent=%s best_score=%s retrieved_chunks=%s",
2285
+ session_id,
2286
+ intent,
2287
+ best_score,
2288
+ len(docs),
2289
+ )
2290
+ response_payload = {
2291
+ "answer": INSUFFICIENT_CONTEXT_MESSAGE,
2292
+ "sources": [],
2293
+ "retrieval_type": "refusal",
2294
+ "mode": mode,
2295
+ "cache_hit": cache_hit,
2296
+ }
2297
+ with sessions_lock:
2298
+ session = sessions.get(session_id)
2299
+ if session:
2300
+ session.setdefault("chat", []).append({
2301
+ "question": question,
2302
+ "answer": INSUFFICIENT_CONTEXT_MESSAGE,
2303
+ "sources": [],
2304
+ "mode": mode
2305
+ })
2306
+ save_sessions_unlocked()
2307
+ return response_payload
2308
+
2309
+ pages = sorted(set(
2310
+ doc.metadata["page"] + 1
2311
+ for doc in docs
2312
+ if "page" in doc.metadata
2313
+ ))
2314
+
2315
+ formatted_context = ""
2316
+
2317
+ for idx, doc in enumerate(docs):
2318
+
2319
+ page = (
2320
+ doc.metadata.get("page", 0) + 1
2321
+ if "page" in doc.metadata
2322
+ else None
2323
+ )
2324
+
2325
+ formatted_context += (
2326
+ f"[Source {idx+1} | Page {page}]\n"
2327
+ f"{doc.page_content}\n\n"
2328
+ )
2329
+
2330
+ context = formatted_context[:6500]
2331
+
2332
+ retrieved_sources = sorted({
2333
+ document_display_name(doc)
2334
+ for doc in docs
2335
+ })
2336
+
2337
+ citation_sources = [
2338
+ citation_source_for_document(doc, idx)
2339
+ for idx, doc in enumerate(docs)
2340
+ ]
2341
+
2342
+ source_id_by_key = {
2343
+ document_dedupe_key(doc): idx + 1
2344
+ for idx, doc in enumerate(docs)
2345
+ }
2346
+
2347
+ if mode == "socratic":
2348
+ framed = apply_mode_framing("", question, mode, docs, context)
2349
+ response_payload = {
2350
+ "answer": framed,
2351
+ "sources": citation_sources,
2352
+ "retrieval_type": "socratic",
2353
+ "cache_hit": cache_hit,
2354
+ "mode": mode,
2355
+ }
2356
+ with sessions_lock:
2357
+ session = sessions.get(session_id)
2358
+ if session:
2359
+ session.setdefault("chat", []).append({
2360
+ "question": question,
2361
+ "answer": framed,
2362
+ "sources": citation_sources,
2363
+ "mode": mode
2364
+ })
2365
+ save_sessions_unlocked()
2366
+ return response_payload
2367
+
2368
+ grounded_answer = build_answer_from_documents(
2369
+ question,
2370
+ docs,
2371
+ intent,
2372
+ source_id_by_key=source_id_by_key,
2373
+ )
2374
+
2375
+ if grounded_answer == INSUFFICIENT_CONTEXT_MESSAGE:
2376
+ logger.info(
2377
+ "Refusing due to insufficient context session_id=%s intent=%s best_score=%s retrieved_chunks=%s sources=%s",
2378
+ session_id,
2379
+ intent,
2380
+ best_score,
2381
+ len(docs),
2382
+ retrieved_sources,
2383
+ )
2384
+ response_payload = {
2385
+ "answer": grounded_answer,
2386
+ "sources": citation_sources,
2387
+ "retrieval_type": "citation-aware",
2388
+ "cache_hit": cache_hit,
2389
+ "mode": mode,
2390
+ }
2391
+ with sessions_lock:
2392
+ session = sessions.get(session_id)
2393
+ if session:
2394
+ session.setdefault("chat", []).append({
2395
+ "question": question,
2396
+ "answer": grounded_answer,
2397
+ "sources": citation_sources,
2398
+ "mode": mode
2399
+ })
2400
+ save_sessions_unlocked()
2401
+ return response_payload
2402
+ if grounded_answer:
2403
+ if ASK_REQUIRE_CITATIONS and not answer_contains_citation(grounded_answer, len(docs)):
2404
+ logger.info(
2405
+ "Refusing due to missing citations session_id=%s intent=%s best_score=%s retrieved_chunks=%s sources=%s",
2406
+ session_id,
2407
+ intent,
2408
+ best_score,
2409
+ len(docs),
2410
+ retrieved_sources,
2411
+ )
2412
+ response_payload = {
2413
+ "answer": INSUFFICIENT_CONTEXT_MESSAGE,
2414
+ "sources": citation_sources,
2415
+ "retrieval_type": "refusal",
2416
+ "mode": mode,
2417
+ "cache_hit": cache_hit,
2418
+ }
2419
+ with sessions_lock:
2420
+ session = sessions.get(session_id)
2421
+ if session:
2422
+ session.setdefault("chat", []).append({
2423
+ "question": question,
2424
+ "answer": INSUFFICIENT_CONTEXT_MESSAGE,
2425
+ "sources": citation_sources,
2426
+ "mode": mode
2427
+ })
2428
+ save_sessions_unlocked()
2429
+ return response_payload
2430
+ logger.info(
2431
+ "Returning grounded answer session_id=%s intent=%s retrieved_chunks=%s sources=%s",
2432
+ session_id,
2433
+ intent,
2434
+ len(docs),
2435
+ retrieved_sources,
2436
+ )
2437
+
2438
+ framed = apply_mode_framing(grounded_answer, question, mode, docs, context)
2439
+
2440
+ # If citations were required and mode-framing stripped them, revert to original.
2441
+ if ASK_REQUIRE_CITATIONS and not answer_contains_citation(framed, len(docs)):
2442
+ logger.info(
2443
+ "Mode framing stripped citations; reverting to grounded answer session_id=%s mode=%s",
2444
+ session_id,
2445
+ mode,
2446
+ )
2447
+ framed = grounded_answer
2448
+
2449
+ result = {
2450
+ "answer": framed,
2451
+ "sources": citation_sources,
2452
+ "retrieval_type": "citation-aware",
2453
+ "cache_hit": cache_hit,
2454
+ "mode": mode,
2455
+ }
2456
+
2457
+ with sessions_lock:
2458
+ session = sessions.get(session_id)
2459
+ if session:
2460
+ session.setdefault("chat", []).append({
2461
+ "question": question,
2462
+ "answer": framed,
2463
+ "sources": citation_sources,
2464
+ "mode": mode
2465
+ })
2466
+ save_sessions_unlocked()
2467
+ return result
2468
+
2469
+ prompt = (
2470
+ "You are a careful assistant answering questions over one or more uploaded PDF documents. "
2471
+ "Use only the provided context. The context may include excerpts from multiple PDFs. "
2472
+ "When the question asks for a relationship, comparison, or synthesis, connect the relevant facts across documents. "
2473
+ "If the context does not contain enough information, say that briefly and do not invent details.\n\n"
2474
+
2475
+ "Reference the provided source numbers naturally whenever the answer is directly supported by the context.\n"
2476
+ "Cite sources using formats like 'According to Source 1' or 'Source 2 explains that...'\n"
2477
+
2478
+ "You are a helpful AI assistant.\n"
2479
+ "Give clear, conversational, human-friendly answers.\n"
2480
+ "Do not return raw PDF text or chunks.\n"
2481
+ "Summarize properly in readable sentences.\n\n"
2482
+
2483
+ f"Context:\n{context}\n\n"
2484
+ f"Question: {question}\n"
2485
+ "Answer:"
2486
+ )
2487
+
2488
+ logger.info(
2489
+ "Executing query session_id=%s retrieved_chunks=%s sources=%s",
2490
+ session_id,
2491
+ len(docs),
2492
+ retrieved_sources,
2493
+ )
2494
+
2495
+ answer = generate_response(
2496
+ prompt,
2497
+ max_new_tokens=256
2498
+ )
2499
+
2500
+ framed = apply_mode_framing(answer, question, mode, docs, context)
2501
+
2502
+ # If citations were required and mode-framing stripped them, revert to original.
2503
+ if ASK_REQUIRE_CITATIONS and not answer_contains_citation(framed, len(docs)):
2504
+ logger.info(
2505
+ "Mode framing stripped citations; reverting to generated answer session_id=%s mode=%s",
2506
+ session_id,
2507
+ mode,
2508
+ )
2509
+ framed = answer
2510
+
2511
+ response_payload = {
2512
+ "answer": framed,
2513
+ "sources": citation_sources,
2514
+ "retrieval_type": "citation-aware",
2515
+ "cache_hit": cache_hit,
2516
+ "mode": mode,
2517
+ }
2518
+
2519
+ with sessions_lock:
2520
+
2521
+ session = sessions.get(session_id)
2522
+
2523
+ if session:
2524
+
2525
+ retrieval_cache = session.setdefault(
2526
+ "retrieval_cache",
2527
+ {}
2528
+ )
2529
+
2530
+ session.setdefault("chat", []).append({
2531
+ "question": question,
2532
+ "answer": framed,
2533
+ "sources": citation_sources,
2534
+ "mode": mode
2535
+ })
2536
+ save_sessions_unlocked()
2537
+
2538
+ return response_payload
2539
+
2540
+ @app.post("/summarize")
2541
+ def summarize_pdf(data: SummarizeRequest):
2542
+ cleanup_expired_sessions()
2543
+ session_id = str(data.session_id)
2544
+ with sessions_lock:
2545
+ session = _touch_session_unlocked(session_id)
2546
+ if not session:
2547
+ raise HTTPException(status_code=404, detail="Session expired or invalid. Please re-upload your PDFs.")
2548
+ _require_session_secret(session, data.session_secret)
2549
+ if "lock" not in session:
2550
+ session["lock"] = threading.Lock()
2551
+ session_lock = session["lock"]
2552
+ if not session.get("vectorstore"):
2553
+ try:
2554
+ session["vectorstore"] = FAISS.load_local(str(FAISS_DIR / session_id), embedding_model, allow_dangerous_deserialization=True)
2555
+ except Exception as e:
2556
+ logger.error(f"Failed to lazy load vectorstore: {e}")
2557
+ raise HTTPException(status_code=500, detail="Failed to load session index.")
2558
+ vectorstore = session["vectorstore"]
2559
+ uploaded_documents = list(session.get("documents", []))
2560
+
2561
+ with session_lock:
2562
+ indexed_documents = collect_index_documents(vectorstore)
2563
+
2564
+ if not uploaded_documents or not indexed_documents:
2565
+ return {"summary": "No document context available to summarize."}
2566
+
2567
+ logger.info(
2568
+ "Summarizing session session_id=%s documents=%s",
2569
+ session_id,
2570
+ len(uploaded_documents),
2571
+ )
2572
+
2573
+ return {"summary": build_session_summary(uploaded_documents, indexed_documents)}
2574
+ if __name__ == "__main__":
2575
+ is_production = os.getenv("ENVIRONMENT", "development").lower() == "production"
2576
+ host = os.getenv("HOST", "0.0.0.0")
2577
+ port = int(os.getenv("PORT", "5000"))
2578
+ uvicorn.run("main:app", host=host, port=port, reload=not is_production)
rag-service/pdf_parse_worker.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def _extract_pdf_text_worker(
2
+ pdf_path: str,
3
+ max_pages: int,
4
+ max_chars: int,
5
+ out_queue,
6
+ ):
7
+ """
8
+ Lightweight PDF parser worker used by multiprocessing spawn.
9
+
10
+ Keep this module free of FastAPI, LangChain, Torch, and Transformers imports.
11
+ On Windows, spawn imports the target function's module in the child process;
12
+ pointing at main.py would load the full RAG stack before parsing starts.
13
+ """
14
+ try:
15
+ from pypdf import PdfReader
16
+
17
+ reader = PdfReader(pdf_path, strict=False)
18
+
19
+ if getattr(reader, "is_encrypted", False):
20
+ try:
21
+ reader.decrypt("")
22
+ except Exception:
23
+ out_queue.put({"ok": False, "error": "Unable to read this PDF. It may be encrypted."})
24
+ return
25
+
26
+ pages = getattr(reader, "pages", [])
27
+ page_count = len(pages)
28
+ if page_count == 0:
29
+ out_queue.put({"ok": False, "error": "No readable pages were found in the PDF."})
30
+ return
31
+ if page_count > max_pages:
32
+ out_queue.put(
33
+ {
34
+ "ok": False,
35
+ "error": f"PDF has too many pages ({page_count}). Max allowed is {max_pages}.",
36
+ "page_count": page_count,
37
+ }
38
+ )
39
+ return
40
+
41
+ extracted = []
42
+ used = 0
43
+ for idx, page in enumerate(pages):
44
+ if idx >= max_pages:
45
+ break
46
+ text = page.extract_text() or ""
47
+ if not text.strip():
48
+ continue
49
+
50
+ remaining = max_chars - used
51
+ if remaining <= 0:
52
+ break
53
+ if len(text) > remaining:
54
+ text = text[:remaining]
55
+ used += len(text)
56
+ extracted.append({"page": idx, "text": text})
57
+
58
+ if not extracted:
59
+ out_queue.put({"ok": False, "error": "No readable text was found in the PDF."})
60
+ return
61
+
62
+ out_queue.put(
63
+ {
64
+ "ok": True,
65
+ "page_count": page_count,
66
+ "extracted": extracted,
67
+ "extracted_chars": used,
68
+ }
69
+ )
70
+ except Exception as exc:
71
+ out_queue.put({"ok": False, "error": "Unable to read this PDF. It may be corrupted.", "details": str(exc)})
rag-service/requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ python-dotenv
4
+ pydantic
5
+ langchain
6
+ langchain-community
7
+ langchain-text-splitters
8
+ sentence-transformers
9
+ transformers
10
+ faiss-cpu
11
+ pypdf
12
+ requests
13
+ numpy
14
+ rank-bm25==0.2.2
15
+ pymongo
16
+ python-multipart
rag-service/scripts/demo_mongodb_pdf_rag.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ # Load .env automatically for local demos (both repo-root and rag-service/.env).
9
+ try: # pragma: no cover
10
+ from dotenv import load_dotenv # type: ignore
11
+
12
+ _here = Path(__file__).resolve()
13
+ _rag_service_root = _here.parents[1]
14
+ _repo_root = _rag_service_root.parent
15
+
16
+ load_dotenv(_repo_root / ".env", override=False)
17
+ load_dotenv(_rag_service_root / ".env", override=False)
18
+ except Exception:
19
+ pass
20
+
21
+ # Allow running as: `python scripts/demo_mongodb_pdf_rag.py` from the rag-service folder.
22
+ # (When executed by path, Python puts `scripts/` on sys.path, not the project root.)
23
+ RAG_SERVICE_ROOT = Path(__file__).resolve().parents[1]
24
+ if str(RAG_SERVICE_ROOT) not in sys.path:
25
+ sys.path.insert(0, str(RAG_SERVICE_ROOT))
26
+
27
+ from crawler.agent import CrawlerAgent # noqa: E402
28
+ from crawler.mongodb_connector import MongoDBConnector # noqa: E402
29
+
30
+
31
+ def _env(name: str, default: Optional[str] = None) -> Optional[str]:
32
+ value = os.getenv(name, default)
33
+ if value is None:
34
+ return None
35
+ value = value.strip()
36
+ return value or None
37
+
38
+
39
+ def main() -> int:
40
+ """
41
+ Demo: MongoDB (unstructured docs that may contain PDFs) -> extracted text -> simple RAG retrieval.
42
+
43
+ This script is meant for screen-recordings / manual verification.
44
+
45
+ Required env:
46
+ - MONGODB_URI
47
+ - MONGO_DB
48
+ - MONGO_COLLECTION
49
+
50
+ Optional env:
51
+ - MONGO_LIMIT (default: 3)
52
+ - RAG_QUERY (default: "What is this document about?")
53
+ """
54
+ mongo_uri = _env("MONGODB_URI")
55
+ mongo_db = _env("MONGO_DB")
56
+ mongo_collection = _env("MONGO_COLLECTION")
57
+
58
+ if not mongo_uri or not mongo_db or not mongo_collection:
59
+ print(
60
+ "Missing required env vars. Set: MONGODB_URI, MONGO_DB, MONGO_COLLECTION",
61
+ file=sys.stderr,
62
+ )
63
+ return 2
64
+
65
+ limit = int(_env("MONGO_LIMIT", "3") or "3")
66
+ query = _env("RAG_QUERY", "What is this document about?") or "What is this document about?"
67
+
68
+ print("[1/5] Connecting to MongoDB…")
69
+ connector = MongoDBConnector(
70
+ uri=mongo_uri,
71
+ database=mongo_db,
72
+ collection=mongo_collection,
73
+ limit=limit,
74
+ )
75
+
76
+ agent = CrawlerAgent(connector=connector, source_name="mongodb")
77
+
78
+ print("[2/5] Extracting Documents (PDF blobs -> text when present)…")
79
+ docs = list(agent.iter_documents())
80
+ print(f" Extracted {len(docs)} document(s)")
81
+ if not docs:
82
+ print(
83
+ "No documents produced. Ensure your collection contains fields like "
84
+ "'pdf_bytes' / 'pdf' / 'pdf_base64' (bytes or base64 text), or adjust the data.",
85
+ file=sys.stderr,
86
+ )
87
+ return 3
88
+
89
+ print("[3/5] Chunking + embedding into FAISS…")
90
+ from langchain_community.embeddings import HuggingFaceEmbeddings
91
+ from langchain_community.vectorstores import FAISS
92
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
93
+
94
+ splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=120)
95
+ chunks = splitter.split_documents(docs)
96
+ print(f" Chunks: {len(chunks)}")
97
+
98
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
99
+ vectorstore = FAISS.from_documents(chunks, embeddings)
100
+
101
+ print("[4/5] Similarity search…")
102
+ results = vectorstore.similarity_search(query, k=3)
103
+ print(f" Query: {query}")
104
+ print(f" Top matches: {len(results)}")
105
+
106
+ print("[5/5] Preview (first match snippet):")
107
+ top = results[0]
108
+ snippet = (top.page_content or "").strip().replace("\n", " ")
109
+ print(f" metadata={top.metadata}")
110
+ print(f" snippet={snippet[:220]}{'…' if len(snippet) > 220 else ''}")
111
+
112
+ return 0
113
+
114
+
115
+ if __name__ == "__main__":
116
+ raise SystemExit(main())
rag-service/test_crawler.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ from pathlib import Path
3
+
4
+ from crawler.agent import CrawlerAgent
5
+ from crawler.base import Record
6
+ from crawler.sqlite_connector import SQLiteConnector
7
+
8
+
9
+ def test_sqlite_connector_emits_documents(tmp_path: Path):
10
+ db_path = tmp_path / "test.db"
11
+ conn = sqlite3.connect(db_path)
12
+ try:
13
+ conn.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, body TEXT)")
14
+ conn.execute("INSERT INTO notes (title, body) VALUES (?, ?)", ("hello", "world"))
15
+ conn.commit()
16
+ finally:
17
+ conn.close()
18
+
19
+ connector = SQLiteConnector(db_path=str(db_path), table="notes")
20
+ agent = CrawlerAgent(connector=connector, source_name="sqlite")
21
+
22
+ docs = list(agent.iter_documents())
23
+ assert len(docs) == 1
24
+ assert "title: hello" in docs[0].page_content
25
+ assert "body: world" in docs[0].page_content
26
+ assert docs[0].metadata["source"] == "sqlite"
27
+ assert docs[0].metadata["entity"] == "notes"
28
+
29
+
30
+ def _make_minimal_pdf_bytes(text: str) -> bytes:
31
+ # Minimal PDF with text, built with correct xref offsets to avoid parser warnings.
32
+ stream = (
33
+ "BT\n"
34
+ "/F1 24 Tf\n"
35
+ "72 72 Td\n"
36
+ f"({text}) Tj\n"
37
+ "ET\n"
38
+ ).encode("ascii")
39
+
40
+ parts: list[bytes] = []
41
+ parts.append(b"%PDF-1.4\n")
42
+
43
+ offsets: list[int] = [0]
44
+
45
+ def add_obj(obj_num: int, body: bytes) -> None:
46
+ offsets.append(sum(len(p) for p in parts))
47
+ parts.append(f"{obj_num} 0 obj\n".encode("ascii"))
48
+ parts.append(body)
49
+ if not body.endswith(b"\n"):
50
+ parts.append(b"\n")
51
+ parts.append(b"endobj\n")
52
+
53
+ add_obj(1, b"<< /Type /Catalog /Pages 2 0 R >>\n")
54
+ add_obj(2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>\n")
55
+ add_obj(
56
+ 3,
57
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 144]\n"
58
+ b"/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\n",
59
+ )
60
+ add_obj(4, b"<< /Length %d >>\nstream\n%s\nendstream\n" % (len(stream), stream))
61
+ add_obj(5, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n")
62
+
63
+ xref_offset = sum(len(p) for p in parts)
64
+ parts.append(b"xref\n0 6\n")
65
+ parts.append(b"0000000000 65535 f \n")
66
+ for off in offsets[1:]:
67
+ parts.append(f"{off:010d} 00000 n \n".encode("ascii"))
68
+ parts.append(b"trailer\n<< /Size 6 /Root 1 0 R >>\n")
69
+ parts.append(b"startxref\n")
70
+ parts.append(f"{xref_offset}\n".encode("ascii"))
71
+ parts.append(b"%%EOF\n")
72
+
73
+ return b"".join(parts)
74
+
75
+
76
+ def test_pdf_blob_field_is_extracted_to_text(tmp_path: Path):
77
+ pdf_bytes = _make_minimal_pdf_bytes("Hello PDF")
78
+
79
+ class FakeConnector:
80
+ def iter_records(self):
81
+ yield Record(
82
+ source="mongodb",
83
+ entity="docs",
84
+ record_id="1",
85
+ fields={"pdf_bytes": pdf_bytes, "title": "example"},
86
+ )
87
+
88
+ agent = CrawlerAgent(connector=FakeConnector(), source_name="mongodb")
89
+ docs = list(agent.iter_documents())
90
+
91
+ assert len(docs) == 1
92
+ assert "Hello PDF" in docs[0].page_content
rag-service/test_legacy_upload_pdf.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import MagicMock
2
+
3
+ # Prevent downloading/loading Hugging Face embeddings during testing by mocking the class
4
+ import langchain_community.embeddings
5
+
6
+ langchain_community.embeddings.HuggingFaceEmbeddings = MagicMock()
7
+
8
+ from fastapi.testclient import TestClient
9
+
10
+ import main
11
+
12
+
13
+ def test_upload_pdf_is_not_exposed_and_not_internal_auth_protected(monkeypatch):
14
+ """
15
+ The legacy /upload_pdf route was removed, but it must not remain in the internal-auth
16
+ allowlist. Otherwise a missing route can incorrectly return 403 instead of 404,
17
+ which is confusing and hides the true behavior.
18
+ """
19
+ monkeypatch.setattr(main, "INTERNAL_RAG_TOKEN", "secret")
20
+
21
+ with main.sessions_lock:
22
+ main.sessions.clear()
23
+
24
+ client = TestClient(main.app)
25
+ res = client.post("/upload_pdf")
26
+ assert res.status_code == 404
27
+
28
+ with main.sessions_lock:
29
+ assert main.sessions == {}
30
+
rag-service/test_main.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from unittest.mock import MagicMock
3
+ import multiprocessing
4
+
5
+ # Prevent downloading/loading Hugging Face embeddings during testing by mocking the class
6
+ import langchain_community.embeddings
7
+ langchain_community.embeddings.HuggingFaceEmbeddings = MagicMock()
8
+
9
+ import pytest
10
+ from fastapi.testclient import TestClient
11
+
12
+ from main import (
13
+ app,
14
+ detect_question_intent,
15
+ sanitize_upload_filename,
16
+ concise_excerpt,
17
+ split_sentences,
18
+ clean_sentence,
19
+ query_keywords,
20
+ tokenize_text,
21
+ build_answer_from_documents,
22
+ INSUFFICIENT_CONTEXT_MESSAGE,
23
+ passes_evidence_gate,
24
+ document_dedupe_key,
25
+ citation_source_for_document,
26
+ internal_token_valid,
27
+ normalize_session_id,
28
+ get_session_dir,
29
+ _extract_pdf_text_worker,
30
+ )
31
+
32
+ import secrets as _secrets
33
+
34
+
35
+ def is_authorized_session_update(session: dict, provided_secret) -> bool:
36
+ """Replicate the session-secret check from the endpoint (moved inline upstream)."""
37
+ expected = (session.get("session_secret") or "").strip()
38
+ candidate = (provided_secret or "").strip()
39
+ if not expected or not candidate:
40
+ return False
41
+ return _secrets.compare_digest(candidate, expected)
42
+
43
+
44
+ def test_session_secret_authorizes_only_matching_secret():
45
+ session = {"session_secret": "expected-secret"}
46
+
47
+ assert is_authorized_session_update(session, "expected-secret") is True
48
+ assert is_authorized_session_update(session, "wrong-secret") is False
49
+ assert is_authorized_session_update(session, None) is False
50
+ assert is_authorized_session_update({}, "expected-secret") is False
51
+
52
+
53
+ def test_detect_question_intent():
54
+ assert detect_question_intent("What is this document about?") == "overview"
55
+ assert detect_question_intent("What are these documents about?") == "overview"
56
+ assert detect_question_intent("Explain the connection between X and Y") == "relationship"
57
+ assert detect_question_intent("How does X compare to Y?") == "comparison"
58
+ assert detect_question_intent("Compare the performance of model A and B") == "comparison"
59
+ assert detect_question_intent("What is the revenue in 2023?") == "factual"
60
+ assert detect_question_intent("Who is the CEO of the company?") == "factual"
61
+
62
+
63
+ def test_sanitize_upload_filename_valid():
64
+ assert sanitize_upload_filename("test.pdf") == "test.pdf"
65
+ assert sanitize_upload_filename("path/to/my_document.PDF") == "my_document.PDF"
66
+ assert sanitize_upload_filename("C:\\Users\\file-name_123.pdf") == "file-name_123.pdf"
67
+
68
+
69
+ def test_sanitize_upload_filename_invalid():
70
+ with pytest.raises(ValueError, match="Missing PDF file path"):
71
+ sanitize_upload_filename("")
72
+
73
+ with pytest.raises(ValueError, match="Missing PDF file path"):
74
+ sanitize_upload_filename(" ")
75
+
76
+ with pytest.raises(ValueError, match="Only PDF files are allowed"):
77
+ sanitize_upload_filename("test.txt")
78
+
79
+ with pytest.raises(ValueError, match="Uploaded filename contains unsupported characters"):
80
+ sanitize_upload_filename("test$file.pdf")
81
+
82
+
83
+ def test_internal_token_valid_allows_when_unset():
84
+ assert internal_token_valid(None, "") is True
85
+ assert internal_token_valid("", "") is True
86
+
87
+
88
+ def test_internal_token_valid_rejects_missing_when_set():
89
+ assert internal_token_valid(None, "secret") is False
90
+ assert internal_token_valid("", "secret") is False
91
+ assert internal_token_valid(" ", "secret") is False
92
+
93
+
94
+ def test_internal_token_valid_accepts_exact_match():
95
+ assert internal_token_valid("secret", "secret") is True
96
+
97
+
98
+ def test_internal_auth_middleware_protects_validate_session_write():
99
+ import main as main_module
100
+
101
+ original_token = main_module.INTERNAL_RAG_TOKEN
102
+ main_module.INTERNAL_RAG_TOKEN = "test-secret"
103
+ try:
104
+ client = TestClient(app)
105
+ response = client.post("/validate-session-write")
106
+ assert response.status_code == 403
107
+ assert response.json()["error"] == "Forbidden"
108
+ finally:
109
+ main_module.INTERNAL_RAG_TOKEN = original_token
110
+
111
+
112
+ def test_normalize_session_id_rejects_invalid_values():
113
+ with pytest.raises(ValueError, match="Missing session id"):
114
+ normalize_session_id("")
115
+
116
+ with pytest.raises(ValueError):
117
+ normalize_session_id("not-a-uuid")
118
+
119
+
120
+ def test_get_session_dir_requires_uuid_session_id():
121
+ with pytest.raises(ValueError):
122
+ get_session_dir("../escape")
123
+
124
+
125
+ def test_normalize_session_id_returns_canonical_uuid():
126
+ normalized = normalize_session_id("550E8400-E29B-41D4-A716-446655440000")
127
+ assert normalized == "550e8400-e29b-41d4-a716-446655440000"
128
+
129
+
130
+ def test_extract_pdf_text_worker_enforces_page_limit(tmp_path):
131
+ from pypdf import PdfWriter
132
+
133
+ pdf_path = tmp_path / "hello.pdf"
134
+ writer = PdfWriter()
135
+ writer.add_blank_page(width=300, height=144)
136
+ with pdf_path.open("wb") as fp:
137
+ writer.write(fp)
138
+
139
+ # Use a local queue and call the worker directly (no subprocess) to validate limit logic.
140
+ q = multiprocessing.Queue(maxsize=1)
141
+ _extract_pdf_text_worker(str(pdf_path), max_pages=0, max_chars=1000, out_queue=q)
142
+ result = q.get(timeout=2)
143
+ assert result["ok"] is False
144
+ assert "too many pages" in result["error"].lower()
145
+
146
+
147
+
148
+ def test_concise_excerpt():
149
+ text = "This is a very long sentence that we want to abbreviate cleanly."
150
+ assert concise_excerpt(text, max_chars=20) == "This is a very long..."
151
+ assert concise_excerpt(text, max_chars=100) == text
152
+
153
+
154
+ def test_split_sentences():
155
+ text = "First sentence! Second sentence. Third one?"
156
+ sentences = split_sentences(text)
157
+
158
+ assert len(sentences) == 3
159
+ assert sentences[0] == "First sentence!"
160
+ assert sentences[1] == "Second sentence."
161
+ assert sentences[2] == "Third one?"
162
+
163
+
164
+ def test_clean_sentence():
165
+ assert clean_sentence(" - Clean this sentence ") == "Clean this sentence"
166
+ assert clean_sentence("* clean me ") == "clean me"
167
+
168
+
169
+ def test_query_keywords():
170
+ # Stopwords like "what", "is", "this", "about" are filtered out
171
+ # Only tokens with length > 2 are kept
172
+ assert query_keywords("What is this document about revenue?") == {"revenue"}
173
+ assert query_keywords("accuracy of model") == {"model", "accuracy"}
174
+
175
+
176
+ def test_empty_query_handling():
177
+ query = ""
178
+ assert query.strip() == ""
179
+
180
+
181
+ def test_invalid_query_type():
182
+ query = None
183
+ assert query is None
184
+
185
+
186
+ def test_context_document_presence():
187
+ docs = ["sample pdf content", "rag pipeline notes"]
188
+ assert len(docs) > 0
189
+
190
+
191
+ def test_answer_response_structure():
192
+ response = {
193
+ "answer": "Sample answer",
194
+ "sources": ["doc1.pdf"]
195
+ }
196
+
197
+ assert "answer" in response
198
+ assert isinstance(response["sources"], list)
199
+
200
+
201
+ def test_db_connection_placeholder():
202
+ db_status = True
203
+ assert db_status is True
204
+
205
+
206
+ def test_query_routing_logic():
207
+ query = "Summarize this PDF"
208
+
209
+ if "summarize" in query.lower():
210
+ route = "summarizer"
211
+ else:
212
+ route = "qa"
213
+
214
+ assert route == "summarizer"
215
+
216
+
217
+ def test_crawler_response_structure():
218
+ crawler_output = {
219
+ "url": "https://example.com",
220
+ "content": "Sample crawled content",
221
+ "status": 200
222
+ }
223
+
224
+ assert "url" in crawler_output
225
+ assert "content" in crawler_output
226
+ assert crawler_output["status"] == 200
227
+
228
+
229
+ def test_crawler_empty_content():
230
+ crawler_output = {
231
+ "url": "https://example.com",
232
+ "content": "",
233
+ "status": 200
234
+ }
235
+
236
+ assert crawler_output["content"] == ""
237
+
238
+
239
+ def test_crawler_failed_status():
240
+ crawler_output = {
241
+ "url": "https://example.com",
242
+ "content": None,
243
+ "status": 500
244
+ }
245
+
246
+ assert crawler_output["status"] >= 400
247
+
248
+
249
+ def test_retry_logic_placeholder():
250
+ retries = 3
251
+ success = True
252
+
253
+ for _ in range(retries):
254
+ success = True
255
+
256
+
257
+ assert success is True
258
+
259
+
260
+ def test_document_extraction_consistency():
261
+ extracted_chunks = [
262
+ "chunk one",
263
+ "chunk two",
264
+ "chunk three"
265
+ ]
266
+
267
+ assert len(extracted_chunks) == 3
268
+ assert all(isinstance(chunk, str) for chunk in extracted_chunks)
269
+
270
+
271
+ def test_crawler_metadata_preservation():
272
+ metadata = {
273
+ "source": "sample.pdf",
274
+ "page": 1
275
+ }
276
+
277
+ assert metadata["source"] == "sample.pdf"
278
+ assert metadata["page"] == 1
279
+
280
+
281
+ def test_empty_document_handling():
282
+ extracted_text = ""
283
+
284
+ assert extracted_text == ""
285
+
286
+
287
+ def test_unstructured_pdf_ingestion_mock():
288
+ mock_document = {
289
+ "filename": "research.pdf",
290
+ "content": "This is extracted PDF content"
291
+ }
292
+
293
+ assert "pdf" in mock_document["filename"]
294
+ assert len(mock_document["content"]) > 0
295
+
296
+
297
+ class DummyDocument:
298
+ def __init__(self, content, filename="doc.pdf", page=0):
299
+ self.page_content = content
300
+ self.metadata = {
301
+ "filename": filename,
302
+ "page": page,
303
+ "document_id": filename,
304
+ }
305
+
306
+
307
+ def test_evidence_gate_refuses_when_overlap_missing():
308
+ docs = [DummyDocument("this is unrelated content", filename="a.pdf", page=0)]
309
+ assert passes_evidence_gate("What is the revenue?", docs, best_score=0.1, intent="factual") is False
310
+
311
+
312
+ def test_evidence_gate_allows_when_overlap_and_score_good():
313
+ docs = [DummyDocument("Revenue for 2023 was 10 million.", filename="a.pdf", page=0)]
314
+ assert passes_evidence_gate("What is the revenue for 2023?", docs, best_score=0.2, intent="factual") is True
315
+
316
+
317
+ def test_build_answer_includes_citations_for_grounded_answer():
318
+ doc = DummyDocument("Revenue for 2023 was 10 million.", filename="a.pdf", page=0)
319
+ source_id_by_key = {document_dedupe_key(doc): 1}
320
+ answer = build_answer_from_documents(
321
+ "What is the revenue for 2023?",
322
+ [doc],
323
+ "factual",
324
+ source_id_by_key=source_id_by_key,
325
+ )
326
+ assert "Source 1" in answer or "Sources 1" in answer
327
+
328
+
329
+ def test_build_answer_refuses_when_unanswerable():
330
+ doc = DummyDocument("This document is about hiring policies.", filename="a.pdf", page=0)
331
+ source_id_by_key = {document_dedupe_key(doc): 1}
332
+ answer = build_answer_from_documents(
333
+ "What is the revenue for 2023?",
334
+ [doc],
335
+ "factual",
336
+ source_id_by_key=source_id_by_key,
337
+ )
338
+ assert answer == INSUFFICIENT_CONTEXT_MESSAGE
339
+
340
+
341
+ def test_citation_source_for_document_preserves_jump_metadata():
342
+ doc = DummyDocument("Internship duration is 6 weeks. More details follow.", filename="policy.pdf", page=11)
343
+ doc.metadata["chunk_index"] = 4
344
+ source = citation_source_for_document(doc, 0)
345
+
346
+ assert source["document"] == "policy.pdf"
347
+ assert source["page"] == 12
348
+ assert source["chunk_index"] == 4
349
+ assert source["text"].startswith("Internship duration")
350
+ assert source["preview"].startswith("Internship duration")
351
+
352
+
353
+ def test_citation_source_for_document_handles_missing_metadata():
354
+ doc = DummyDocument("Useful supporting text.", filename="", page=0)
355
+ doc.metadata = {}
356
+ source = citation_source_for_document(doc, 2)
357
+
358
+ assert source["document"] == "uploaded document"
359
+ assert source["page"] is None
360
+ assert source["chunk_index"] == 2
rag-service/test_processing_status.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import MagicMock
2
+
3
+ # Prevent downloading/loading Hugging Face embeddings during testing by mocking the class
4
+ import langchain_community.embeddings
5
+
6
+ langchain_community.embeddings.HuggingFaceEmbeddings = MagicMock()
7
+
8
+ from fastapi.testclient import TestClient
9
+
10
+ import main
11
+
12
+
13
+ def test_processing_status_requires_internal_token_when_enabled(monkeypatch):
14
+ monkeypatch.setattr(main, "INTERNAL_RAG_TOKEN", "secret")
15
+
16
+ with main.sessions_lock:
17
+ main.sessions.clear()
18
+
19
+ client = TestClient(main.app)
20
+ res = client.get("/processing-status/00000000-0000-0000-0000-000000000000")
21
+ assert res.status_code == 403
22
+
23
+ res = client.get(
24
+ "/processing-status/00000000-0000-0000-0000-000000000000",
25
+ headers={"X-Internal-Token": "secret"},
26
+ )
27
+ assert res.status_code == 404
28
+
29
+
30
+ def test_processing_status_is_pruned_with_session_ttl(monkeypatch):
31
+ monkeypatch.setattr(main, "INTERNAL_RAG_TOKEN", "secret")
32
+
33
+ session_id = "11111111-1111-1111-1111-111111111111"
34
+ now = main.now_ts()
35
+
36
+ with main.sessions_lock:
37
+ main.sessions.clear()
38
+ main.sessions[session_id] = {
39
+ "vectorstore": None,
40
+ "lock": None,
41
+ "documents": [],
42
+ "session_secret": "s",
43
+ "session_dir": None,
44
+ "created_at": now - 100,
45
+ "last_accessed": now - 100,
46
+ "retrieval_cache": {},
47
+ "processing_progress": {"stage": "Starting", "progress": 5, "updated_at": now - 100},
48
+ }
49
+
50
+ client = TestClient(main.app)
51
+
52
+ # With a long TTL, the status should be available.
53
+ monkeypatch.setattr(main, "SESSION_TTL_MINUTES", 60)
54
+ res = client.get(f"/processing-status/{session_id}", headers={"X-Internal-Token": "secret"})
55
+ assert res.status_code == 200
56
+ assert res.json()["stage"] == "Starting"
57
+
58
+ # With a zero TTL, the session should be pruned and status should disappear.
59
+ monkeypatch.setattr(main, "SESSION_TTL_MINUTES", 0)
60
+ res = client.get(f"/processing-status/{session_id}", headers={"X-Internal-Token": "secret"})
61
+ assert res.status_code == 404
62
+