File size: 6,619 Bytes
35fbb15
 
c6aa66a
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35fbb15
 
 
 
c6aa66a
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import os
import json
import re
from pathlib import Path
from dotenv import load_dotenv
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings
from langchain_community.vectorstores import FAISS

load_dotenv(Path(__file__).parent.parent / ".env")

VECTOR_DB_PATH = Path(__file__).parent.parent / "vector_db"
DOCUMENTS_PATH = Path(__file__).parent.parent / "documents"
IMAGES_PATH    = Path(__file__).parent.parent / "images"

CHUNK_SIZE    = 1000
CHUNK_OVERLAP = 200
MIN_IMAGE_DIM = 80   # pixels β€” skip tiny icons / decorative elements


def get_embeddings() -> NVIDIAEmbeddings:
    return NVIDIAEmbeddings(
        model="nvidia/nv-embedqa-e5-v5",
        api_key=os.environ["NVIDIA_API_KEY"],
        truncate="END",
    )


# ── Image extraction ──────────────────────────────────────────────────────────

def extract_images_from_pdf(pdf_path: str) -> dict[int, list[str]]:
    """
    Extract images from every page of the PDF using PyMuPDF.
    Returns a dict mapping  page_number (0-based) β†’ [image_filename, ...]
    Only images larger than MIN_IMAGE_DIM Γ— MIN_IMAGE_DIM are kept.
    """
    try:
        import fitz  # PyMuPDF
    except ImportError:
        return {}

    pdf_name = Path(pdf_path).stem
    page_images: dict[int, list[str]] = {}
    doc = fitz.open(pdf_path)

    for page_num in range(len(doc)):
        page = doc[page_num]
        img_list = page.get_images(full=True)
        saved = []

        for img_idx, img_info in enumerate(img_list):
            xref = img_info[0]
            try:
                base = doc.extract_image(xref)
            except Exception:
                continue

            w, h = base.get("width", 0), base.get("height", 0)
            if w < MIN_IMAGE_DIM or h < MIN_IMAGE_DIM:
                continue

            ext = base.get("ext", "png")
            filename = f"{pdf_name}_p{page_num + 1}_i{img_idx + 1}.{ext}"
            dest = IMAGES_PATH / filename

            if not dest.exists():
                dest.write_bytes(base["image"])

            saved.append(filename)

        if saved:
            page_images[page_num] = saved

    doc.close()
    return page_images


# ── Text ingestion ────────────────────────────────────────────────────────────

_COMMON_WORDS = frozenset(
    "the of and to in a is for be or by on with as at an are shall will "
    "not this that from any university policy student students".split()
)


def _english_ratio(text: str) -> float:
    words = re.findall(r"[a-zA-Z]+", text.lower())
    if not words:
        return 1.0  # nothing to judge β€” leave the page alone
    return sum(w in _COMMON_WORDS for w in words) / len(words)


def _repair_shifted_text(text: str) -> str:
    """Some PDFs embed fonts with a custom encoding that stores every
    character shifted by a constant (and no ToUnicode map), so extractors
    return gibberish like '3/$*,$5,60' for 'PLAGIARISM'. If a page doesn't
    look like English, try constant shifts and keep the best-scoring one."""
    if _english_ratio(text) > 0.08:
        return text

    best, best_ratio = text, _english_ratio(text)
    for shift in range(1, 33):
        decoded = "".join(
            chr(o + shift) if 0x20 <= (o := ord(c)) + shift <= 0x7E else c
            for c in text
        )
        ratio = _english_ratio(decoded)
        if ratio > best_ratio:
            best, best_ratio = decoded, ratio

    # Only accept a repair that clearly turned into English
    return best if best_ratio > 0.12 else text


def load_and_split_pdf(pdf_path: str, page_images: dict[int, list[str]]) -> list:
    loader = PyPDFLoader(pdf_path)
    pages = loader.load()

    for page in pages:
        page.page_content = _repair_shifted_text(page.page_content)

    splitter = RecursiveCharacterTextSplitter(
        chunk_size=CHUNK_SIZE,
        chunk_overlap=CHUNK_OVERLAP,
        separators=["\n\n", "\n", ".", " ", ""],
    )
    chunks = splitter.split_documents(pages)

    for chunk in chunks:
        page_num = chunk.metadata.get("page", 0)   # PyPDFLoader uses 0-based page
        chunk.metadata["source"] = Path(pdf_path).name
        # Attach image filenames for this page (stored as JSON string)
        imgs = page_images.get(page_num, [])
        chunk.metadata["images"] = json.dumps(imgs)

    return chunks


def ingest_pdf(pdf_path: str) -> int:
    """
    Extract images, embed text chunks, merge into persisted FAISS index.
    Returns the number of text chunks added.
    """
    page_images = extract_images_from_pdf(pdf_path)
    chunks = load_and_split_pdf(pdf_path, page_images)

    if not chunks:
        return 0

    embeddings = get_embeddings()
    index_file = VECTOR_DB_PATH / "index.faiss"

    if index_file.exists():
        store = FAISS.load_local(
            str(VECTOR_DB_PATH),
            embeddings,
            allow_dangerous_deserialization=True,
        )
        store.add_documents(chunks)
    else:
        store = FAISS.from_documents(chunks, embeddings)

    store.save_local(str(VECTOR_DB_PATH))
    return len(chunks)


def remove_pdf(filename: str) -> int:
    """Remove a document: delete its chunks from the FAISS index (by docstore
    id β€” no re-embedding needed), the PDF file, and its extracted images.
    Returns the number of chunks removed."""
    removed = 0
    store = load_vector_store()
    if store is not None:
        ids = [
            doc_id
            for doc_id, doc in getattr(store.docstore, "_dict", {}).items()
            if doc.metadata.get("source") == filename
        ]
        if ids:
            store.delete(ids)
            store.save_local(str(VECTOR_DB_PATH))
            removed = len(ids)

    (DOCUMENTS_PATH / filename).unlink(missing_ok=True)
    stem = Path(filename).stem
    for img in IMAGES_PATH.glob(f"{stem}_p*_i*.*"):
        img.unlink(missing_ok=True)
    return removed


def load_vector_store() -> FAISS | None:
    """Load the persisted FAISS index. Returns None if no index exists yet."""
    index_file = VECTOR_DB_PATH / "index.faiss"
    if not index_file.exists():
        return None
    embeddings = get_embeddings()
    return FAISS.load_local(
        str(VECTOR_DB_PATH),
        embeddings,
        allow_dangerous_deserialization=True,
    )