htr-tiny / htr /parse /pdf.py
spboucher04's picture
Release HTR-Tiny-0.3.0 (WP-AI-0002)
ff8d20f verified
Raw History Blame Contribute Delete
35.7 kB
"""PDF parser (PyMuPDF) for born-digital journal articles (Crossref / publisher PDFs).
Pipeline: spans → visual lines (fragments sharing a baseline are merged) → running header/footer and
page-number removal → small-print, equation and table-row filtering → heading / inline-label / caption
detection → paragraph reconstruction (indentation, short last line, vertical gap, page continuation) with
hyphenation repair → section roles via ``htr.parse.jats.section_role``. Everything from the first
``References | Bibliography | Works Cited`` heading onwards is cut; acknowledgement-like back-matter
sections are dropped. Bibliographic fields (title, authors, date, licence) come from the manifest stub,
which carries the provider evidence; the parser only cross-checks a licence URL printed in the PDF.
The output ``ParsedDocument`` has the same contract as ``parse_jats``: ``body_text`` is the concatenation
of paragraph texts each followed by a blank line, and ``char_start``/``char_end`` index into it.
"""
from __future__ import annotations
import datetime as _dt
import math
import re
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
from htr.licenses.policy import normalize_license
from htr.parse.jats import EXCLUDED_SECTION_TITLES, ParsedDocument, ParsedParagraph, section_role
from htr.parse.protect import protect
from htr.parse.quality import quality_score
from htr.utils.text import normalize_text
# ---------------------------------------------------------------------------------------------------------
# Patterns
REFERENCES_RE = re.compile(r"^\s*(?:[\dIVX]+\.?\s*)?(?:references?(?: and notes)?|bibliography|works cited|literature cited|reference list|literature)\s*:?\s*$", re.I)
LOCAL_EXCLUDED_RE = re.compile(r"authors?['’]?s?['’]?\s+contributions?|^\s*(?:end)?notes\s*$|author details|publisher['’]?s note|additional information|^\s*keywords?\b|^\s*key words\b|^\s*jel\b|nomenclature|^\s*notation\s*$|^\s*open access\s*$|data availability|^\s*credit\b", re.I)
KNOWN_LABEL_RE = re.compile(
r"^\s*(abstract|summary|keywords?|key words|jel(?:\s+(?:classification|codes?))?(?:\s+codes?)?|acknowledge?ments?|author contributions?|"
r"conflicts? of interest|funding|abbreviations|supplementary materials?|data availability(?: statement)?|introduction)\s*[:.]",
re.I,
)
KNOWN_HEADING_RE = re.compile(r"^\s*(?:[\dIVX]+\.?\s*)?(abstract|introduction|background|conclusions?|concluding remarks|discussion|results|methods?|methodology|data|references|bibliography|acknowledge?ments?|appendix(?:\s+[A-Z\d])?)\s*$", re.I)
NUMBERED_RE = re.compile(r"^\s*((?:\d{1,2}(?:\.\d{1,2}){0,3})\.?|[IVX]{1,5}\.|[A-H]\.(?:\d{1,2}\.?)*)\s+(\S.*)$")
CAPTION_RE = re.compile(r"^\s*(Table|Figure|Fig\.|Chart|Exhibit|Graph)\s*[A-Z]?\d+[a-z]?(?:\.\d+)?\s*(?:[.:|—–-]|$)", re.I)
CAPTION_LOOSE_RE = re.compile(r"^\s*(Table|Figure|Fig\.|Chart|Exhibit)\s*[A-Z]?\d+[a-z]?\s+[A-Z(]")
PAGE_NUM_RE = re.compile(r"^\s*(?:page\s*)?[\divxlc]{1,5}(?:\s*(?:of|/)\s*\d{1,4})?\s*$", re.I)
MARGIN_BOILER_RE = re.compile(r"\bdoi[:\s]|https?://|www\.|©|\bpage \d+ of \d+|\bvol(?:ume)?\.?\s*\d+", re.I)
FRONT_BOILER_RE = re.compile(r"^\s*(?:received|accepted|published(?: online)?|revised|academic editors?|correspondence|\*\s*correspondence|citation|copyright|©|e-?mail|tel\.|fax|issn|open access|article|review|research|original article|www\.|https?://)\b", re.I)
TERMINAL_RE = re.compile(r"[.!?][\"”’')\]]*$")
MATH_FONT_RE = re.compile(r"CM(?:EX|MI|SY|R|BX)\d|MSAM|MSBM|Math|Symbol|MT-?Extra|Euclid|STIX|rsfs|Cambria\s*Math|Mathematica|Pazo", re.I)
MATH_CHARS = set("=+−×÷∑∫∏√∞≤≥≈≠∂∇∈∉⊂⊆∪∩→←↔⇒⇔∀∃αβγδεζηθικλμνξπρστυφχψωΓΔΘΛΞΠΣΦΨΩ^_|")
WORD_RE = re.compile(r"[A-Za-z]+")
BOLD_FONT_RE = re.compile(r"bold|black|heavy|semibold|demi|[-,]b[do]?\b|\bbd\b", re.I)
ITALIC_FONT_RE = re.compile(r"ital|oblique|[-,]it\b", re.I)
@dataclass
class _Line:
page: int
block: int
x0: float
y0: float
x1: float
y1: float
size: float
text: str
font: str
bold: bool
italic: bool
lead_bold: str # text of the leading run of bold spans
math_frac: float
n_chars: int
kind: str = "text" # text | heading | label | caption | equation | table | dropped
meta: dict = field(default_factory=dict)
# ---------------------------------------------------------------------------------------------------------
# Extraction
def _is_bold(span: dict) -> bool:
return bool(span.get("flags", 0) & 16) or bool(BOLD_FONT_RE.search(span.get("font", "")))
def _is_italic(span: dict) -> bool:
return bool(span.get("flags", 0) & 2) or bool(ITALIC_FONT_RE.search(span.get("font", "")))
def _line_from_spans(page: int, block: int, bbox, spans: list[dict]) -> _Line | None:
spans = [s for s in spans if s.get("text")]
if not spans:
return None
sizes = Counter()
fonts = Counter()
for s in spans:
n = len(s["text"].strip())
sizes[round(s["size"] * 2) / 2] += n
fonts[s.get("font", "")] += n
main_size = sizes.most_common(1)[0][0] if sizes else spans[0]["size"]
# Drop raised small numeric spans (footnote markers such as "media1"); keep sub/superscripts in math.
parts: list[str] = []
prev_txt = ""
baseline = max((s["bbox"][3] for s in spans if abs(s["size"] - main_size) < 0.6), default=bbox[3])
prev_x1: float | None = None
for s in spans:
t = s["text"]
raised = s["bbox"][3] < baseline - 0.25 * main_size
if raised and s["size"] < 0.8 * main_size and re.fullmatch(r"\s*[\d,*†‡§¶–-]{1,7}\s*", t) and re.search(r"[A-Za-z.,;:)”’]$", prev_txt):
continue
if prev_x1 is not None and parts and not parts[-1].endswith(" ") and not t.startswith(" ") and s["bbox"][0] - prev_x1 > 0.2 * main_size:
parts.append(" ")
parts.append(t)
prev_x1 = s["bbox"][2]
prev_txt = (prev_txt + t)[-5:]
text = "".join(parts)
if not text.strip():
return None
n_chars = sum(1 for c in text if not c.isspace())
math_chars = sum(len(s["text"].strip()) for s in spans if MATH_FONT_RE.search(s.get("font", "")))
alpha_spans = [s for s in spans if re.search(r"[A-Za-z]", s["text"])]
bold = bool(alpha_spans) and all(_is_bold(s) for s in alpha_spans)
italic = bool(alpha_spans) and all(_is_italic(s) for s in alpha_spans)
lead = []
for s in spans:
if _is_bold(s) or not s["text"].strip():
lead.append(s["text"])
else:
break
return _Line(page, block, bbox[0], bbox[1], bbox[2], bbox[3], float(main_size), text, fonts.most_common(1)[0][0], bold, italic, "".join(lead).strip(), math_chars / max(1, n_chars), n_chars)
def _merge_visual_lines(lines: list[_Line], two_col: bool) -> list[_Line]:
"""Merge consecutive fragments that share a baseline (PyMuPDF splits lines at font/spacing changes)."""
out: list[_Line] = []
for ln in lines:
if out:
p = out[-1]
h = min(p.y1 - p.y0, ln.y1 - ln.y0) or 1.0
overlap = min(p.y1, ln.y1) - max(p.y0, ln.y0)
gap = ln.x0 - p.x1
max_gap = (1.0 if two_col else 2.2) * max(p.size, ln.size)
if overlap >= 0.4 * h and -1.0 <= gap <= max_gap and bool(p.meta.get("frag")) == bool(ln.meta.get("frag")):
if gap > 0.9 * max(p.size, ln.size):
p.meta["wide_gaps"] = p.meta.get("wide_gaps", 0) + 1 # cell-like spacing (table rows)
sep = "" if (p.text.endswith(" ") or ln.text.startswith(" ")) else " "
n = p.n_chars + ln.n_chars
p.math_frac = (p.math_frac * p.n_chars + ln.math_frac * ln.n_chars) / max(1, n)
p.text = p.text + sep + ln.text
p.x1 = max(p.x1, ln.x1)
p.y0, p.y1 = min(p.y0, ln.y0), max(p.y1, ln.y1)
if ln.n_chars > p.n_chars:
p.size, p.font = ln.size, ln.font
p.n_chars = n
p.bold = p.bold and ln.bold if re.search(r"[A-Za-z]", ln.text) else p.bold
continue
out.append(ln)
return out
def _two_column(lines: list[_Line], width: float) -> bool:
body = [ln for ln in lines if ln.n_chars >= 20]
if len(body) < 12:
return False
mid = width / 2
narrow = [ln for ln in body if (ln.x1 - ln.x0) < 0.48 * width]
left = sum(1 for ln in narrow if ln.x1 <= mid + 5)
right = sum(1 for ln in narrow if ln.x0 >= mid - 5)
return len(narrow) >= 0.5 * len(body) and left >= 4 and right >= 4
def _order_two_column(lines: list[_Line], width: float) -> list[_Line]:
"""Reading order for a two-column page: full-width lines act as band separators; within a band, the
left column is read before the right column."""
mid = width / 2
srt = sorted(lines, key=lambda ln: (ln.y0, ln.x0))
out: list[_Line] = []
band: list[_Line] = []
def flush() -> None:
left = [ln for ln in band if ln.x0 < mid - 5]
right = [ln for ln in band if ln.x0 >= mid - 5]
out.extend(sorted(left, key=lambda ln: (ln.y0, ln.x0)))
out.extend(sorted(right, key=lambda ln: (ln.y0, ln.x0)))
band.clear()
for ln in srt:
if (ln.x1 - ln.x0) > 0.6 * width or (ln.x0 < mid - 20 and ln.x1 > mid + 20):
flush()
out.append(ln)
else:
band.append(ln)
flush()
return out
def _mode(values: list[float], default: float) -> float:
if not values:
return default
return Counter(values).most_common(1)[0][0]
# ---------------------------------------------------------------------------------------------------------
# Line classification helpers
def _is_terminal(text: str) -> bool:
return bool(TERMINAL_RE.search(text.rstrip()))
def _starts_lower(text: str) -> bool:
t = text.lstrip(" \"“‘'([")
return bool(t) and t[0].islower()
def _is_table_line(text: str) -> bool:
toks = text.split()
if not toks:
return False
nonspace = sum(len(t) for t in toks)
digits = sum(c.isdigit() for c in text)
words = [w for w in WORD_RE.findall(text) if len(w) >= 4]
numeric_toks = sum(1 for t in toks if re.fullmatch(r"[(\[]?[-−+]?[\d.,]+%?[)\]]?\**", t))
if len(toks) >= 2 and digits / max(1, nonspace) > 0.4:
return True
if numeric_toks >= 3 and numeric_toks >= 0.5 * len(toks):
return True
if len(toks) >= 5 and nonspace / len(toks) <= 3.2 and len(words) <= 1:
return True
return False
def _is_equation_line(ln: _Line) -> bool:
t = ln.text.strip()
if not t:
return False
if ln.math_frac > 0.4:
return True
nonspace = [c for c in t if not c.isspace()]
alpha = sum(c.isalpha() and c.isascii() for c in nonspace)
words3 = [w for w in WORD_RE.findall(t) if len(w) >= 3]
mathc = sum(c in MATH_CHARS for c in nonspace)
if alpha / max(1, len(nonspace)) < 0.5 and len(words3) <= 2 and len(nonspace) >= 3:
return True
if mathc >= 2 and len(words3) <= 2:
return True
if re.search(r"\(\s*[A-Z]?\d{1,3}[a-z]?\s*\)\s*$", t) and len(words3) <= 3 and mathc >= 1:
return True
return False
def _heading_depth(text: str, size_level: int) -> int:
m = NUMBERED_RE.match(text)
if m:
num = m.group(1).rstrip(".")
if re.fullmatch(r"\d+(?:\.\d+)*", num):
return num.count(".") + 1
if re.fullmatch(r"[A-H](?:\.\d+)*", num):
return num.count(".") + 1
return 1
return size_level
# ---------------------------------------------------------------------------------------------------------
# Main entry point
def parse_pdf(path: Path | str, stub: dict | None = None) -> ParsedDocument:
import fitz # PyMuPDF
stub = stub or {}
path = Path(path)
doc = fitz.open(str(path))
warnings: list[str] = []
n_pages = doc.page_count
raw_pages: list[list[_Line]] = []
page_dims: list[tuple[float, float]] = []
raw_text_chars = 0
raw_text_all: list[str] = []
two_col_pages = 0
for pno in range(n_pages):
page = doc[pno]
w, h = page.rect.width, page.rect.height
page_dims.append((w, h))
d = page.get_text("dict")
lines: list[_Line] = []
for b in d.get("blocks", []):
if b.get("type") != 0:
continue
for li in b.get("lines", []):
ln = _line_from_spans(pno, b.get("number", 0), li["bbox"], li.get("spans", []))
if ln is not None:
lines.append(ln)
raw_text_chars += ln.n_chars
raw_text_all.append(ln.text)
# Blocks made only of tiny glyph fragments are display equations typeset glyph by glyph
by_block: dict[int, list[_Line]] = {}
for ln in lines:
by_block.setdefault(ln.block, []).append(ln)
for blines in by_block.values():
txt = " ".join(x.text for x in blines)
if sum(x.n_chars for x in blines) / len(blines) < 6 and not any(len(wd) >= 4 for wd in WORD_RE.findall(txt)):
for x in blines:
x.meta["frag"] = True
tc = _two_column(lines, w)
if tc:
two_col_pages += 1
lines = _order_two_column(lines, w)
lines = _merge_visual_lines(lines, tc)
for ln in lines:
ln.meta["two_col"] = tc
raw_pages.append(lines)
doc.close()
if n_pages == 0 or raw_text_chars < 30 * max(1, n_pages) * 0.5:
raise ValueError("no text layer")
if raw_text_chars / max(1, n_pages) < 800:
warnings.append(f"low_text_density={raw_text_chars / max(1, n_pages):.0f} chars/page")
if two_col_pages:
warnings.append(f"two_column_pages={two_col_pages}/{n_pages}")
warnings.append(f"pdf_pages={n_pages}")
# Licence statement printed in the PDF (cross-check only; the stub's provider evidence is authoritative)
joined_raw = " ".join(raw_text_all)
m_lic = re.search(r"creativecommons\.org/(?:licenses|publicdomain)/[a-z\-]+(?:/\d\.\d)?", joined_raw, re.I)
stub_lic = (stub.get("license") or {}).get("code", "UNKNOWN")
if m_lic:
pdf_code = normalize_license(None, m_lic.group(0))
if pdf_code != stub_lic:
warnings.append(f"license statement in PDF ({pdf_code}, {m_lic.group(0)}) differs from provider ({stub_lic})")
# Body font size / font (character-weighted modes)
size_ctr: Counter = Counter()
font_ctr: Counter = Counter()
for lines in raw_pages:
for ln in lines:
size_ctr[ln.size] += ln.n_chars
font_ctr[ln.font] += ln.n_chars
body_size = size_ctr.most_common(1)[0][0] if size_ctr else 10.0
body_font = font_ctr.most_common(1)[0][0] if font_ctr else ""
total_chars = sum(font_ctr.values()) or 1
rare_fonts = {f for f, c in font_ctr.items() if c / total_chars < 0.06}
# ---- running headers / footers / page numbers
def _key(t: str) -> str:
return re.sub(r"\d+", "#", re.sub(r"\s+", " ", t.strip().lower()))
key_pages: dict[str, set[int]] = {}
for lines in raw_pages:
for ln in lines:
_, h = page_dims[ln.page]
if ln.y1 < 0.13 * h or ln.y0 > 0.88 * h:
key_pages.setdefault(_key(ln.text), set()).add(ln.page)
threshold = max(2, math.ceil(0.4 * n_pages))
n_hf = 0
for lines in raw_pages:
for ln in lines:
_, h = page_dims[ln.page]
in_margin = ln.y1 < 0.13 * h or ln.y0 > 0.88 * h
if not in_margin:
continue
if ln.page == 0 and ln.y1 < 0.13 * h:
ln.kind, ln.meta["why"] = "dropped", "first_page_masthead"
n_hf += 1
continue
k = _key(ln.text)
if len(key_pages.get(k, ())) >= threshold or PAGE_NUM_RE.match(ln.text) or (MARGIN_BOILER_RE.search(ln.text) and len(ln.text) < 160):
ln.kind = "dropped"
ln.meta["why"] = "header_footer"
n_hf += 1
if n_hf:
warnings.append(f"headers_footers_removed={n_hf}")
# ---- caption blocks (kept even when set in small print)
caption_blocks: set[tuple[int, int]] = set()
for lines in raw_pages:
seen_blocks: set[int] = set()
for ln in lines:
if ln.kind == "dropped" or ln.block in seen_blocks:
continue
seen_blocks.add(ln.block)
if CAPTION_RE.match(ln.text) or (CAPTION_LOOSE_RE.match(ln.text) and (ln.lead_bold or ln.font != body_font)):
caption_blocks.add((ln.page, ln.block))
# ---- per-line classification: small print, equations, tables, front-page boilerplate
stream: list[_Line] = []
n_small = n_eq = n_tab = 0
for lines in raw_pages:
for ln in lines:
if ln.kind == "dropped":
continue
in_caption = (ln.page, ln.block) in caption_blocks
if REFERENCES_RE.match(normalize_text(ln.text)):
# detected before the small-print filter: some publishers set the back matter in small type
ln.kind = "heading"
ln.meta.update(depth=1, title=normalize_text(ln.text))
stream.append(ln)
continue
if not in_caption and ln.size < 0.85 * body_size:
ln.kind, ln.meta["why"] = "dropped", "small_font"
n_small += 1
continue
if not in_caption and (ln.meta.get("frag") or _is_equation_line(ln)):
ln.kind = "equation"
n_eq += 1
elif not in_caption and (_is_table_line(ln.text) or ln.meta.get("wide_gaps", 0) >= 2):
ln.kind = "table"
n_tab += 1
elif ln.page <= 1 and FRONT_BOILER_RE.match(ln.text) and not KNOWN_LABEL_RE.match(ln.text) and len(ln.text) < 200 and not _is_terminal(ln.text[:0] or "x"):
# Short boilerplate lines (received/accepted dates, editors, correspondence) on the first pages
if len(WORD_RE.findall(ln.text)) <= 30:
ln.kind, ln.meta["why"] = "dropped", "front_boilerplate"
continue
stream.append(ln)
for name, n in (("dropped_small_font_lines", n_small), ("dropped_equation_lines", n_eq), ("dropped_table_lines", n_tab)):
if n:
warnings.append(f"{name}={n}")
# ---- geometry statistics
margins: dict[int, float] = {}
rights: dict[int, float] = {}
for pno in range(n_pages):
xs = [round(ln.x0) for ln in stream if ln.page == pno and ln.kind == "text" and abs(ln.size - body_size) < 1.0]
x1s = sorted(ln.x1 for ln in stream if ln.page == pno and ln.kind == "text" and abs(ln.size - body_size) < 1.0)
margins[pno] = _mode(xs, min(xs) if xs else 0.0)
rights[pno] = x1s[int(0.8 * (len(x1s) - 1))] if x1s else page_dims[pno][0]
pitches = [b.y0 - a.y0 for a, b in zip(stream, stream[1:]) if a.page == b.page and 0 < b.y0 - a.y0 < 3 * body_size and a.kind == b.kind == "text"]
pitch = sorted(pitches)[len(pitches) // 2] if pitches else 1.2 * body_size
block_min: dict[tuple[int, int], float] = {}
block_n: Counter = Counter()
for ln in stream:
if ln.kind == "text":
k = (ln.page, ln.block)
block_min[k] = min(block_min.get(k, ln.x0), ln.x0)
block_n[k] += 1
# ---- headings and inline labels
def heading_style(ln: _Line) -> tuple[bool, int]:
if ln.size >= body_size + 1.5:
return True, 1
if ln.size >= body_size + 0.4:
return True, 1 if not ln.italic else 2
if ln.bold:
return True, 1 if not ln.italic else 2
if ln.font != body_font and ln.font in rare_fonts and not MATH_FONT_RE.search(ln.font):
return True, 2 if ln.italic else 1
return False, 1
def standalone(i: int) -> bool:
if i == 0:
return True
p = stream[i - 1]
ln = stream[i]
if p.kind in ("heading", "label", "equation", "table") or p.page != ln.page or p.block != ln.block:
return True
if _is_terminal(p.text):
return True
return (ln.y0 - p.y0) > 1.5 * pitch
for i, ln in enumerate(stream):
if ln.kind != "text":
continue
t = normalize_text(ln.text)
# Inline labels: "Abstract: ...", "Keywords: ...", "Acknowledgments: ..." (bold run-in or known word)
mlab = KNOWN_LABEL_RE.match(t)
lead = normalize_text(ln.lead_bold)
if mlab and (standalone(i) or lead):
label = mlab.group(1)
rest = t[mlab.end():].strip()
if rest:
ln.kind = "label"
ln.meta["label"] = label
ln.meta["rest"] = rest
continue
if ((ln.page, ln.block) in caption_blocks and (CAPTION_RE.match(t) or CAPTION_LOOSE_RE.match(t))) or (CAPTION_RE.match(t) and standalone(i) and not _starts_lower(t)):
ln.kind = "caption"
continue
n_words = len(t.split())
if n_words == 0 or n_words > 14 or len(t) > 120 or re.search(r"[,;]$", t) or len(WORD_RE.findall(t)) == 0:
continue
if not (t[0].isupper() or t[0].isdigit()):
continue
if CAPTION_RE.match(t):
continue
body_t = NUMBERED_RE.match(t).group(2) if NUMBERED_RE.match(t) else t
nonsp = [c for c in body_t if not c.isspace()]
if not any(len(w) >= 3 for w in WORD_RE.findall(body_t)) or any(c in MATH_CHARS for c in body_t) or sum(c.isalpha() for c in nonsp) < 0.6 * max(1, len(nonsp)):
continue
styled, level = heading_style(ln)
numbered = bool(NUMBERED_RE.match(t)) and not _is_terminal(t)
known = bool(KNOWN_HEADING_RE.match(t))
nxt = stream[i + 1] if i + 1 < len(stream) else None
short_line = ln.x1 < rights.get(ln.page, ln.x1) - 2 * body_size or n_words <= 8
if not short_line or not standalone(i):
continue
if REFERENCES_RE.match(t) or known or (styled and (numbered or not t.endswith("."))) or (numbered and n_words <= 10 and (nxt is None or nxt.y0 - ln.y0 > 1.15 * pitch or nxt.x0 > ln.x0 + 0.5 * body_size)):
if t.endswith(".") and not numbered and not known and n_words > 6:
continue
ln.kind = "heading"
ln.meta["depth"] = _heading_depth(t, level)
ln.meta["title"] = t
# Merge wrapped multi-line headings
for i in range(1, len(stream)):
p, ln = stream[i - 1], stream[i]
if p.kind == "heading" and ln.kind == "heading" and not NUMBERED_RE.match(ln.meta["title"]) and p.page == ln.page and (ln.y0 - p.y0) < 1.6 * max(pitch, p.size) and not REFERENCES_RE.match(ln.meta["title"]) and not KNOWN_HEADING_RE.match(ln.meta["title"]) and abs(p.size - ln.size) < 0.6:
ln.meta["title"] = p.meta["title"] + " " + ln.meta["title"]
ln.meta["depth"] = p.meta["depth"]
p.kind = "dropped"
p.meta["why"] = "merged_heading"
# ---- front matter: drop everything before the first heading/label if it occurs on the first two pages
def _structural(ln: _Line) -> bool:
if ln.kind == "label":
return True
if ln.kind != "heading":
return False
t = ln.meta["title"]
return bool(KNOWN_HEADING_RE.match(t) or NUMBERED_RE.match(t) or REFERENCES_RE.match(t))
first_struct = next((i for i, ln in enumerate(stream) if _structural(ln) and ln.page <= 1), None)
if first_struct is None:
first_struct = next((i for i, ln in enumerate(stream) if ln.kind in ("heading", "label")), None)
start = 0
if first_struct is not None and stream[first_struct].page <= 1:
start = first_struct
n_front = sum(1 for ln in stream[:first_struct] if ln.kind != "dropped")
if n_front:
warnings.append(f"front_matter_dropped_lines={n_front}")
else:
warnings.append("no_heading_on_first_pages")
# ---- vocabulary for hyphenation repair (excluding the fragments around line-end hyphens)
vocab: Counter = Counter()
prev_hyph = False
for ln in stream:
if ln.kind not in ("text", "label", "caption"):
continue
toks = WORD_RE.findall(ln.text)
hy = bool(re.search(r"[A-Za-z][-‐­]\s*$", ln.text))
if prev_hyph and toks:
toks = toks[1:]
if hy and toks:
toks = toks[:-1]
vocab.update(t.lower() for t in toks)
# hyphenated compounds observed inside lines
for comp in re.findall(r"[A-Za-z]+-[A-Za-z]+", ln.text):
vocab["#" + comp.lower()] += 1
prev_hyph = hy
# ---- paragraph assembly
paragraphs: list[ParsedParagraph] = []
body_parts: list[str] = []
cursor = 0
pidx = 0
n_dehyph = n_kept = 0
cur_lines: list[str] = []
cur_flags: set[str] = set()
last: _Line | None = None
pending_math = False
sec = {"id": "front", "title": None, "role": "other", "depth": 1}
role_stack: list[tuple[int, str]] = []
sec_counter = 0
skipping = False
cut_at: int | None = None
def join_line(prev_text: str, nxt: str) -> tuple[str, str | None]:
"""Join ``nxt`` to the accumulated ``prev_text`` repairing end-of-line hyphenation."""
nonlocal n_dehyph, n_kept
nxt = nxt.strip()
if not prev_text:
return nxt, None
if prev_text.endswith("­"):
n_dehyph += 1
return prev_text[:-1] + nxt, "dehyphenated"
m = re.search(r"([A-Za-z]+)[-‐]$", prev_text)
if m and _starts_lower(nxt) and not prev_text.endswith("--"):
prefix = m.group(1)
msuf = re.match(r"([a-z]+)", nxt)
suffix = msuf.group(1) if msuf else ""
joined = (prefix + suffix).lower()
if suffix and (vocab.get(joined, 0) > 0 and not vocab.get("#" + prefix.lower() + "-" + suffix, 0)):
n_dehyph += 1
return prev_text[:-1] + nxt, "dehyphenated"
if vocab.get("#" + prefix.lower() + "-" + suffix, 0) or (len(prefix) >= 2 and vocab.get(prefix.lower(), 0) > 0 and (vocab.get(suffix, 0) > 0 or len(suffix) <= 2)):
n_kept += 1
return prev_text + nxt, "hyphen_kept"
n_dehyph += 1
return prev_text[:-1] + nxt, "dehyphenated_guess"
if m and nxt[:1].isupper():
return prev_text + nxt, None # "Fin-" + "Tech" → "Fin-Tech"
return prev_text + " " + nxt, None
captions: list[list[str]] = [] # captions seen while a body paragraph was open (emitted after it)
cap_lines: list[str] | None = None
cap_last: _Line | None = None
table_region = False
n_table_region = 0
def _emit(lines: list[str], flags: set[str], role: str) -> None:
nonlocal cursor, pidx
acc = ""
for piece in lines:
acc, fl = join_line(acc, piece)
if fl:
flags.add(fl)
text = re.sub(r"\s+", " ", normalize_text(acc.replace("\n", " "))).strip()
if not text or not WORD_RE.search(text):
return
pr = protect(text)
start_c = cursor
body_parts.append(text + "\n\n")
cursor += len(text) + 2
paragraphs.append(ParsedParagraph(sec["id"], sec["title"], role, sec["depth"], pidx, text, start_c, start_c + len(text), pr.citations, pr.math, pr.urls, pr.numbers, sorted(flags)))
pidx += 1
def end_caption() -> None:
nonlocal cap_lines, cap_last
if cap_lines:
captions.append(cap_lines)
cap_lines, cap_last = None, None
def flush() -> None:
nonlocal cur_lines, cur_flags
end_caption()
if cur_lines and not skipping:
_emit(cur_lines, cur_flags, sec["role"])
if not skipping:
for c in captions:
_emit(c, {"caption"}, "caption")
captions.clear()
cur_lines = []
cur_flags = set()
def open_section(title: str, depth: int, forced_role: str | None = None) -> None:
nonlocal sec_counter, skipping, sec
flush()
if EXCLUDED_SECTION_TITLES.search(title) or LOCAL_EXCLUDED_RE.search(title):
skipping = True
return
skipping = False
sec_counter += 1
role = forced_role or section_role(title, depth)
while role_stack and role_stack[-1][0] >= depth:
role_stack.pop()
if role == "other" and role_stack:
role = role_stack[-1][1]
role_stack.append((depth, role))
sec = {"id": "abstract" if role == "abstract" else f"s{sec_counter}", "title": title, "role": role, "depth": depth}
def new_paragraph_needed(p: _Line, ln: _Line) -> bool:
term = _is_terminal(p.text)
size = ln.size or body_size
if ln.page != p.page or (ln.meta.get("two_col") and ln.x0 > p.x1):
# page or column break: continue unless the previous paragraph visibly ended
margin = margins.get(ln.page, ln.x0)
indent = 0.6 * size < (ln.x0 - margin) < 8 * size
p_short = p.x1 < rights.get(p.page, p.x1) - 2.5 * size
return term and (indent or p_short)
bkey = (ln.page, ln.block)
ref_left = block_min.get(bkey, margins.get(ln.page, ln.x0)) if block_n[bkey] >= 3 else margins.get(ln.page, ln.x0)
indent = 0.6 * size < (ln.x0 - ref_left) < 8 * size
p_short = p.x1 < rights.get(p.page, p.x1) - 2.5 * size
big_gap = (ln.y0 - p.y0) > 1.6 * pitch
if term and (indent or p_short or big_gap):
return True
if big_gap and not _starts_lower(ln.text) and p.block != ln.block and not p.text.rstrip().endswith(("-", ",")):
return True
return False
for i in range(start, len(stream)):
ln = stream[i]
if ln.kind == "dropped":
continue
if ln.kind == "heading":
title = ln.meta["title"]
if table_region and not (NUMBERED_RE.match(title) or KNOWN_HEADING_RE.match(title) or REFERENCES_RE.match(title)):
n_table_region += 1 # bold column headers inside a table body are not section headings
continue
if REFERENCES_RE.match(title):
cut_at = ln.page
break
open_section(title, ln.meta.get("depth", 1), "abstract" if re.match(r"^\s*abstract\s*$", title, re.I) else None)
last, pending_math, table_region = None, False, False
continue
if ln.kind == "label":
label = ln.meta["label"]
low = label.lower()
if low in ("abstract", "summary"):
open_section("Abstract", 1, "abstract")
elif low == "introduction":
open_section("Introduction", 1)
else:
open_section(label, 1)
last, pending_math = None, False
if not skipping:
cur_lines.append(ln.meta["rest"])
last = ln
continue
if ln.kind == "equation":
if cur_lines:
pending_math = True
continue
if ln.kind == "table":
continue
if skipping:
last = ln
continue
if ln.kind == "caption":
# Captions are buffered so that a body paragraph interrupted by a float is not split.
end_caption()
cap_lines, cap_last = [ln.text], ln
table_region = bool(re.match(r"\s*Table", ln.text, re.I))
if not cur_lines:
flush()
continue
if cap_lines is not None and cap_last is not None:
same_block = (ln.page, ln.block) == (cap_last.page, cap_last.block)
if same_block and not new_paragraph_needed(cap_last, ln):
cap_lines.append(ln.text)
cap_last = ln
continue
end_caption()
if table_region:
# Table bodies set at body size (common in MDPI PDFs) follow the "Table N." caption: drop lines
# until the first prose-like line (long, full-width or sentence-final).
n_w = len(ln.text.split())
span = rights.get(ln.page, ln.x1) - margins.get(ln.page, ln.x0)
prose_like = n_w >= 8 and not ln.meta.get("wide_gaps") and ((ln.x1 - ln.x0) >= 0.6 * span or _is_terminal(ln.text)) and not _is_table_line(ln.text)
if not prose_like:
n_table_region += 1
continue
table_region = False
# plain text line
if last is not None and cur_lines:
if new_paragraph_needed(last, ln) and not (_starts_lower(ln.text) and not _is_terminal(last.text)):
flush()
pending_math = False
elif pending_math:
cur_lines.append("⟦MATH⟧")
cur_flags.add("has_disp_formula")
pending_math = False
if cur_lines and last.page != ln.page:
cur_flags.add("crosses_page")
cur_lines.append(ln.text)
last = ln
flush()
if n_table_region:
warnings.append(f"dropped_table_region_lines={n_table_region}")
if cut_at is not None:
warnings.append(f"references_cut_at_page={cut_at + 1}")
else:
warnings.append("no_references_heading")
if n_dehyph or n_kept:
warnings.append(f"dehyphenated={n_dehyph} hyphen_kept={n_kept}")
if sec_counter == 0:
warnings.append("no_headings_detected")
if not paragraphs:
warnings.append("no paragraphs extracted")
good = sum(1 for p in paragraphs if p.section_role != "caption" and quality_score(p.text)[0] >= 0.6)
tot = sum(1 for p in paragraphs if p.section_role != "caption")
warnings.append(f"extraction_quality={good / tot if tot else 0.0:.2f} ({good}/{tot} paragraphs quality>=0.6)")
pub_date = stub.get("pub_date")
pub_year = stub.get("pub_year") or (int(pub_date[:4]) if pub_date else None)
pre2018 = False
if pub_date:
iso = pub_date + ("-01" if len(pub_date) == 7 else "-01-01" if len(pub_date) == 4 else "")
try:
pre2018 = _dt.date.fromisoformat(iso) < _dt.date(2018, 1, 1)
except ValueError:
pre2018 = False
lic = stub.get("license") or {}
ids = {"doi": stub["source_ids"]["doi"]} if stub.get("source_ids", {}).get("doi") else {}
return ParsedDocument(
title=stub.get("title"),
authors=list(stub.get("authors") or []),
author_group=stub.get("author_group"),
venue=stub.get("venue"),
publisher=stub.get("publisher"),
doc_type=stub.get("doc_type") or "article",
pub_date=pub_date,
pub_year=pub_year,
pub_date_evidence=stub.get("pub_date_evidence"),
pre2018_verified=pre2018 and bool(stub.get("pub_date_evidence")),
subjects=list(stub.get("subject_raw") or []),
language=stub.get("language"),
license_code=lic.get("code", "UNKNOWN"),
license_uri=lic.get("uri"),
license_evidence=lic.get("evidence"),
body_text="".join(body_parts),
paragraphs=paragraphs,
warnings=warnings,
article_type=stub.get("doc_type"),
ids=ids,
)