Spaces:
Sleeping
Sleeping
Download backend/ingest.py from Abdullah0327/Docent-AI-ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 6.62 kB
-
https://huggingface.co/spaces/Abdullah0327/Docent-AI-ChatBot/resolve/main/backend/ingest.py
- Command line
-
hf download hf://spaces/Abdullah0327/Docent-AI-ChatBot/backend/ingest.py
-
curl -L -o ingest.py https://huggingface.co/spaces/Abdullah0327/Docent-AI-ChatBot/resolve/main/backend/ingest.py
6.62 kB
| 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, | |
| ) | |