EvidenceGuard-AI / src /document_processor.py
leeshal's picture
Upload 55 files
a805048 verified
Raw History Blame Contribute Delete
5.86 kB
"""PDF ingestion: text extraction, cleaning, metadata detection and sentence-aware chunking."""
from __future__ import annotations
import json
import re
from dataclasses import asdict, dataclass, field
from pathlib import Path
import config
from src.text_utils import split_sentences
_BANNER = re.compile(r"SYNTHETIC DEMONSTRATION DATA.*?policy", re.I)
_FOOTER = re.compile(r"^[A-Z]{2,}/[A-Z0-9/.-]+\s*\|.*$|^Page \d+ of \d+$", re.I)
_DATE_ISO = re.compile(r"\b(20\d{2})-(\d{2})-(\d{2})\b")
_DATE_LONG = re.compile(r"\b(\d{1,2})\s+(January|February|March|April|May|June|July|August|September|"
r"October|November|December)\s+(20\d{2})\b", re.I)
_MONTHS = {m: i for i, m in enumerate(["january", "february", "march", "april", "may", "june", "july",
"august", "september", "october", "november", "december"], 1)}
@dataclass
class Chunk:
chunk_id: str
doc_id: str
doc_name: str
title: str
page: int
text: str
issued: str = "" # ISO date if known; used to decide which version is newer
def to_dict(self):
return asdict(self)
@dataclass
class DocumentInfo:
doc_id: str
doc_name: str
title: str
pages: int
chunks: int
issued: str = ""
status: str = "ok"
message: str = ""
page_texts: list = field(default_factory=list, repr=False)
def extract_pages(path: str | Path) -> list[str]:
"""Return raw text of every page. PyMuPDF first, pypdf as a fallback."""
return extract_pdf(path)[0]
def extract_pdf(path: str | Path) -> tuple[list[str], str]:
"""(page texts, metadata title)."""
try:
import pymupdf
with pymupdf.open(str(path)) as pdf:
return [p.get_text() for p in pdf], (pdf.metadata or {}).get("title", "") or ""
except Exception:
from pypdf import PdfReader
r = PdfReader(str(path))
title = (r.metadata.title if r.metadata and r.metadata.title else "") or ""
return [(p.extract_text() or "") for p in r.pages], title
def clean_page(text: str) -> str:
text = _BANNER.sub(" ", text or "")
lines = []
for ln in text.splitlines():
s = ln.strip()
if not s or _FOOTER.match(s):
continue
words = re.sub(r"^\d+\.\s*", "", s).split()
# Short Title-Case lines without punctuation are headings ("2. Late Submission"):
# terminate them so they become their own sentence instead of gluing onto the next one.
if (words and len(words) <= 7 and s[-1] not in ".:;,)" and words[0][0].isupper()
and all(w[0].isupper() or not w[0].isalpha() for w in words if w.lower() not in
{"and", "of", "the", "for", "to", "in", "on", "a", "-"})):
s += "."
lines.append(s)
text = "\n".join(lines)
text = re.sub(r"(\w)-\n(\w)", r"\1\2", text) # de-hyphenate line breaks
text = re.sub(r"\s*\n\s*", " ", text)
return re.sub(r"\s{2,}", " ", text).strip()
def _to_iso(text: str) -> str:
m = re.search(r"Issued\s+(20\d{2}-\d{2}-\d{2})", text)
if m:
return m.group(1)
m = _DATE_ISO.search(text)
if m:
return m.group(0)
m = _DATE_LONG.search(text)
if m:
d, mon, y = m.groups()
return f"{y}-{_MONTHS[mon.lower()]:02d}-{int(d):02d}"
return ""
def _manifest() -> dict:
p = config.SAMPLE_DATA_DIR / "corpus_manifest.json"
if p.exists():
return {m["filename"]: m for m in json.loads(p.read_text())}
return {}
def chunk_page(sentences: list[str], target_words: int, overlap: int) -> list[str]:
chunks, cur, words = [], [], 0
for s in sentences:
n = len(s.split())
if cur and words + n > target_words:
chunks.append(" ".join(cur))
cur = cur[-overlap:] if overlap else []
words = sum(len(x.split()) for x in cur)
cur.append(s)
words += n
if cur:
tail = " ".join(cur)
if not chunks or tail not in chunks[-1]:
chunks.append(tail)
return chunks
def process_pdf(path: str | Path, doc_id: str | None = None,
target_words: int | None = None, overlap: int | None = None) -> tuple[DocumentInfo, list[Chunk]]:
path = Path(path)
target_words = target_words or config.CHUNK_TARGET_WORDS
overlap = config.CHUNK_OVERLAP_SENTENCES if overlap is None else overlap
doc_id = doc_id or re.sub(r"[^A-Za-z0-9]+", "_", path.stem)[:40]
try:
raw, meta_title = extract_pdf(path)
except Exception as e: # corrupt / encrypted PDF
return DocumentInfo(doc_id, path.name, path.stem, 0, 0, status="error", message=str(e)), []
pages = [clean_page(p) for p in raw]
meta = _manifest().get(path.name, {})
first_line = next((ln.strip() for ln in (raw[0] if raw else "").splitlines()
if ln.strip() and not _BANNER.search(ln)), "")
title = meta.get("title") or (meta_title.strip() if meta_title.strip().strip("()").lower() not in ("", "untitled", "anonymous") else "") \
or first_line[:90] or path.stem
title = re.sub(r"^Aranya Valley University \(AVU\) \(fictional\)\s*", "", title).strip() or path.stem
issued = meta.get("issued") or _to_iso(" ".join(raw[:1]))
chunks: list[Chunk] = []
for pno, text in enumerate(pages, 1):
sents = split_sentences(text)
for ci, ctext in enumerate(chunk_page(sents, target_words, overlap)):
chunks.append(Chunk(f"{doc_id}-p{pno}-c{ci}", doc_id, path.name, title, pno, ctext, issued))
status, msg = "ok", "extracted"
if not any(p.strip() for p in pages):
status, msg = "warning", "no extractable text (scanned PDF? OCR is not supported)"
return DocumentInfo(doc_id, path.name, title, len(pages), len(chunks), issued, status, msg, pages), chunks