Spaces:
Running on Zero
Running on Zero
File size: 5,861 Bytes
a805048 | 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 | """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
|