jimnoneill commited on
Commit
1a48207
·
verified ·
1 Parent(s): 16cb4b7

Retrained head (CC0/CC-BY corpus, poster2json first-page text) and package sync (v0.3.0)

Browse files

Head retrained on the 3,235-document corpus in which every document carries a CC0, CC-BY, or equivalent permissive license, with first-page text read by the poster2json layout engine: held-out 94.4% (95% CI 92.0 to 96.2), nested out-of-fold 94.4%, deployment 80.4% posters over 30,139 PDFs. src/ now mirrors the poster-sentry package 0.3.0 (stacked head support, pdfplumber/pypdfium2 backend, vendored poster2json text path, CLI); install instructions point to the poster-sentry repository.

README.md CHANGED
@@ -35,7 +35,8 @@ Developed by the [**FAIR Data Innovations Hub**](https://fairdataihub.org/) at t
35
 
36
  | Version | Date | Notes |
37
  |---------|------|-------|
38
- | **1.3.0** | 2026-09-21 | License-screened retrain: 84 documents whose source-repository licenses do not permit redistribution were removed, and the head was retrained on the resulting 3,298-document corpus. Held-out accuracy 93.1%. |
 
39
  | **1.2.0** | 2026-09-01 | Stacked head: the 512-d text embedding is scored by a stage-one logistic regression whose poster probability becomes a single text-score feature for the final classifier over [text_score + 15 visual + 15 structural] = 31 features. Held-out accuracy 92.9%. Head weights now store a zero first column so softmax reproduces sklearn's sigmoid exactly; earlier heads doubled the logit, which sharpened reported confidences (decisions at 0.5 were unaffected). Flat heads remain loadable by the package. |
40
  | **1.1.0** | 2026-08-28 | Feature extraction moved off the AGPL-licensed PyMuPDF to pdfplumber (text and structure) and pypdfium2 (page rendering), both permissively licensed, so the whole stack is MIT-compatible. The head was retrained on the re-extracted features; held-out accuracy is 89.2%. |
41
  | **1.0.0** | 2026-08-18 | Head trained on the human-validated corpus: 3,381 documents labeled by a three-reviewer survey (Krippendorff's alpha 0.79) with blinded adjudication of the 439 contested documents. |
@@ -49,7 +50,7 @@ Earlier unversioned weights (April 2026) were trained on heuristically labeled d
49
  | **PosterSentry** | Multimodal poster classifier (this model) | [fairdataihub/poster-sentry](https://huggingface.co/fairdataihub/poster-sentry) |
50
  | **poster-sentry** | Installable classifier package | [GitHub](https://github.com/fairdataihub/poster-sentry) |
51
  | **poster-sentry-training** | Training code and replication | [GitHub](https://github.com/fairdataihub/poster-sentry-training) |
52
- | **poster-sentry-training-data** | Human-validated training dataset (3,298 samples) | [HuggingFace](https://huggingface.co/datasets/fairdataihub/poster-sentry-training-data) |
53
  | **poster-sentry-evaluation-paper-code** | Reproducible analysis for the paper | [GitHub](https://github.com/fairdataihub/poster-sentry-evaluation-paper-code) |
54
  | **Llama-3.1-8B-Poster-Extraction** | Poster → structured JSON extraction | [fairdataihub/Llama-3.1-8B-Poster-Extraction](https://huggingface.co/fairdataihub/Llama-3.1-8B-Poster-Extraction) |
55
  | **poster2json** | Python library for poster extraction | [PyPI](https://pypi.org/project/poster2json/) · [Docs](https://fairdataihub.github.io/poster2json/) · [GitHub](https://github.com/fairdataihub/poster2json) |
@@ -102,16 +103,16 @@ Evaluated against human-validated labels (three-reviewer survey with blinded adj
102
 
103
  | Metric | Value |
104
  |--------|-------|
105
- | **Held-out accuracy** (495 documents) | **93.1%** (95% CI 90.6 to 95.0) |
106
- | Macro F1 (held-out) | 0.931 |
107
- | Precision / Recall / F1 (poster) | 0.918 / 0.948 / 0.933 |
108
- | Precision / Recall / F1 (non-poster) | 0.946 / 0.915 / 0.930 |
109
- | Nested out-of-fold accuracy (all 3,298 documents, 5-fold) | 93.9% |
110
- | Panel reliability with the model as a fourth rater | alpha 0.792 -> 0.795 (unchanged) |
111
- | Calibration (out-of-fold) | Brier 0.046, ECE 0.016 |
112
  | Classifier speed | under one second per file on a CPU (PDF parsing is the bottleneck) |
113
 
114
- Errors concentrate where the human panel itself divided: out-of-fold agreement is 96.4% on documents the panel rated unanimously and 77.3% on documents decided two to one.
115
 
116
  ### Top Features by Importance
117
 
@@ -119,29 +120,29 @@ Standardized logistic regression coefficients of the trained head (positive push
119
 
120
  | Rank | Feature | Coefficient | Signal |
121
  |------|---------|------------|--------|
122
- | 1 | `page_count` | -3.26 | More pages pushes away from poster |
123
- | 2 | `size_per_page_kb` | +2.42 | Dense, high-resolution single pages |
124
- | 3 | `line_count` | +1.94 | Posters pack many short text lines |
125
- | 4 | `file_size_kb` | -1.70 | Multi-page documents are bigger overall |
126
- | 5 | `mean_g` | +1.10 | Colorful, non-white pages |
127
- | 6 | `is_landscape` | +1.00 | Many posters are landscape |
128
- | 7 | `white_space_ratio` | -0.95 | Sparse, white pages push toward non-poster |
129
- | 8 | `edge_density` | +0.86 | Visually busy layouts |
130
- | 9 | `page_width_pt` | +0.80 | Posters are physically wide |
131
- | 10 | `img_width` | +0.79 | Large rendered width |
132
-
133
- Every coefficient of the final classifier is a named feature; the whole text channel enters as the single `text_score` (+0.68, rank 13 of 31), whose value concentrates on the documents where geometry misleads.
134
 
135
  ## Training Data
136
 
137
- Trained on **3,298 documents with human-validated labels**, zero synthetic data:
138
 
139
  | Class | Count | Label provenance |
140
  |-------|-------|------------------|
141
- | **Poster** | 1,651 | Three-reviewer survey; unanimous panel label or blinded adjudication |
142
- | **Non-poster** | 1,647 | Three-reviewer survey; unanimous panel label or blinded adjudication |
143
 
144
- Three reviewers independently rated 3,486 candidate documents that passed license screening (inter-rater Krippendorff's alpha 0.79); the 430 documents without a unanimous panel were settled in a blinded adjudication review. After removing 181 near-duplicate documents and 7 with unavailable PDFs, the remaining 3,298 form the training corpus. Applied to the full corpus of 30,139 readable repository PDFs labeled as posters, PosterSentry classifies 80.5% as posters: roughly one in five records labeled as posters is something else.
145
 
146
  Training data: [fairdataihub/poster-sentry-training-data](https://huggingface.co/datasets/fairdataihub/poster-sentry-training-data)
147
 
@@ -167,21 +168,17 @@ results = sentry.classify_batch(["poster1.pdf", "paper.pdf", "newsletter.pdf"])
167
  ### Installation
168
 
169
  ```bash
170
- pip install git+https://github.com/fairdataihub/poster-repo-qc.git
171
 
172
  # Or install from source
173
- git clone https://github.com/fairdataihub/poster-repo-qc.git
174
- cd poster-repo-qc
175
- pip install -e ".[train]"
176
  ```
177
 
178
  ### Training
179
 
180
- ```bash
181
- python scripts/train_poster_sentry.py --n-per-class 2000
182
- ```
183
-
184
- Training completes in ~40 minutes on CPU (PDF rendering is the bottleneck, not the classifier).
185
 
186
  ## Model Specifications
187
 
@@ -212,7 +209,7 @@ Training completes in ~40 minutes on CPU (PDF rendering is the bottleneck, not t
212
  title = {PosterSentry: Multimodal Scientific Poster Classifier},
213
  author = {O'Neill, Jamey and Portillo, Dorian and Zeinali, Nahid and Soundarajan, Sanjay and Blake, Gerard and Sarin, Parth and Buttrick, Adam and Patel, Bhavesh},
214
  year = {2026},
215
- version = {1.3.0},
216
  url = {https://huggingface.co/fairdataihub/poster-sentry},
217
  note = {Part of the posters.science initiative}
218
  }
 
35
 
36
  | Version | Date | Notes |
37
  |---------|------|-------|
38
+ | **1.4.0** | 2026-10-28 | Trained on the 3,235-document corpus in which every document carries a CC0, CC-BY, or equivalent permissive license, with first-page text read by the poster2json layout engine (vendored in the package). Held-out accuracy 94.4% (95% CI 92.0 to 96.2), nested out-of-fold 94.4%; deployment 80.4% posters. |
39
+ | 1.3.0 | 2026-09-21 | License-screened retrain: 84 documents whose source-repository licenses do not permit redistribution were removed, and the head was retrained on the resulting 3,298-document corpus. Held-out accuracy 93.1%. |
40
  | **1.2.0** | 2026-09-01 | Stacked head: the 512-d text embedding is scored by a stage-one logistic regression whose poster probability becomes a single text-score feature for the final classifier over [text_score + 15 visual + 15 structural] = 31 features. Held-out accuracy 92.9%. Head weights now store a zero first column so softmax reproduces sklearn's sigmoid exactly; earlier heads doubled the logit, which sharpened reported confidences (decisions at 0.5 were unaffected). Flat heads remain loadable by the package. |
41
  | **1.1.0** | 2026-08-28 | Feature extraction moved off the AGPL-licensed PyMuPDF to pdfplumber (text and structure) and pypdfium2 (page rendering), both permissively licensed, so the whole stack is MIT-compatible. The head was retrained on the re-extracted features; held-out accuracy is 89.2%. |
42
  | **1.0.0** | 2026-08-18 | Head trained on the human-validated corpus: 3,381 documents labeled by a three-reviewer survey (Krippendorff's alpha 0.79) with blinded adjudication of the 439 contested documents. |
 
50
  | **PosterSentry** | Multimodal poster classifier (this model) | [fairdataihub/poster-sentry](https://huggingface.co/fairdataihub/poster-sentry) |
51
  | **poster-sentry** | Installable classifier package | [GitHub](https://github.com/fairdataihub/poster-sentry) |
52
  | **poster-sentry-training** | Training code and replication | [GitHub](https://github.com/fairdataihub/poster-sentry-training) |
53
+ | **poster-sentry-training-data** | Human-validated training dataset (3,235 samples, with text and feature values) | [HuggingFace](https://huggingface.co/datasets/fairdataihub/poster-sentry-training-data) |
54
  | **poster-sentry-evaluation-paper-code** | Reproducible analysis for the paper | [GitHub](https://github.com/fairdataihub/poster-sentry-evaluation-paper-code) |
55
  | **Llama-3.1-8B-Poster-Extraction** | Poster → structured JSON extraction | [fairdataihub/Llama-3.1-8B-Poster-Extraction](https://huggingface.co/fairdataihub/Llama-3.1-8B-Poster-Extraction) |
56
  | **poster2json** | Python library for poster extraction | [PyPI](https://pypi.org/project/poster2json/) · [Docs](https://fairdataihub.github.io/poster2json/) · [GitHub](https://github.com/fairdataihub/poster2json) |
 
103
 
104
  | Metric | Value |
105
  |--------|-------|
106
+ | **Held-out accuracy** (486 documents) | **94.4%** (95% CI 92.0 to 96.2) |
107
+ | Macro F1 (held-out) | 0.944 |
108
+ | Precision / Recall / F1 (poster) | 0.953 / 0.934 / 0.943 |
109
+ | Precision / Recall / F1 (non-poster) | 0.936 / 0.955 / 0.945 |
110
+ | Nested out-of-fold accuracy (all 3,235 documents, 5-fold) | 94.4% |
111
+ | Panel reliability with the model as a fourth rater | alpha 0.793 -> 0.798 (unchanged) |
112
+ | Calibration (out-of-fold) | Brier 0.045, ECE 0.016 |
113
  | Classifier speed | under one second per file on a CPU (PDF parsing is the bottleneck) |
114
 
115
+ Errors concentrate where the human panel itself divided: out-of-fold agreement is 96.7% on documents the panel rated unanimously and 79.7% on documents decided two to one.
116
 
117
  ### Top Features by Importance
118
 
 
120
 
121
  | Rank | Feature | Coefficient | Signal |
122
  |------|---------|------------|--------|
123
+ | 1 | `page_count` | -3.47 | More pages pushes away from poster |
124
+ | 2 | `size_per_page_kb` | +2.61 | Dense, high-resolution single pages |
125
+ | 3 | `line_count` | +1.88 | Posters pack many short text lines |
126
+ | 4 | `file_size_kb` | -1.76 | Multi-page documents are bigger overall |
127
+ | 5 | `mean_g` | +1.21 | Colorful, non-white pages |
128
+ | 6 | `is_landscape` | +1.06 | Many posters are landscape |
129
+ | 7 | `white_space_ratio` | -0.92 | Sparse, white pages push toward non-poster |
130
+ | 8 | `page_area_sqin` | -0.83 | Very large page areas push toward non-poster |
131
+ | 9 | `edge_density` | +0.78 | Visually busy layouts |
132
+ | 10 | `color_diversity` | +0.73 | Many distinct colors |
133
+
134
+ Every coefficient of the final classifier is a named feature; the whole text channel enters as the single `text_score` (+0.60, rank 11 of 31). First-page text is read with the poster2json layout engine, which rebuilds the reading order of multi-column layouts.
135
 
136
  ## Training Data
137
 
138
+ Trained on **3,235 documents with human-validated labels**, zero synthetic data:
139
 
140
  | Class | Count | Label provenance |
141
  |-------|-------|------------------|
142
+ | **Poster** | 1,605 | Three-reviewer survey; unanimous panel label or blinded adjudication |
143
+ | **Non-poster** | 1,630 | Three-reviewer survey; unanimous panel label or blinded adjudication |
144
 
145
+ Three reviewers independently rated 3,414 candidate documents, each released by its depositor under CC0, CC-BY, or an equivalent permissive license (inter-rater Krippendorff's alpha 0.79); the 420 documents without a unanimous panel were settled in a blinded adjudication review. After removing 172 near-duplicate documents and 7 with unavailable PDFs, the remaining 3,235 form the training corpus. Applied to the full corpus of 30,139 readable repository PDFs labeled as posters, PosterSentry classifies 80.4% as posters: roughly one in five records labeled as posters is something else.
146
 
147
  Training data: [fairdataihub/poster-sentry-training-data](https://huggingface.co/datasets/fairdataihub/poster-sentry-training-data)
148
 
 
168
  ### Installation
169
 
170
  ```bash
171
+ pip install git+https://github.com/fairdataihub/poster-sentry.git
172
 
173
  # Or install from source
174
+ git clone https://github.com/fairdataihub/poster-sentry.git
175
+ cd poster-sentry
176
+ pip install -e ".[dev]"
177
  ```
178
 
179
  ### Training
180
 
181
+ The as-run training script is `scripts/train_poster_sentry.py` (also at [poster-sentry-training](https://github.com/fairdataihub/poster-sentry-training)). It needs the source PDFs; the [training dataset](https://huggingface.co/datasets/fairdataihub/poster-sentry-training-data) holds the extracted text and every feature value, enough to refit the head without them. Feature extraction for the 3,235 training PDFs takes about 13 minutes on 12 CPU processes (PDF parsing and rendering are the bottleneck, not the classifier).
 
 
 
 
182
 
183
  ## Model Specifications
184
 
 
209
  title = {PosterSentry: Multimodal Scientific Poster Classifier},
210
  author = {O'Neill, Jamey and Portillo, Dorian and Zeinali, Nahid and Soundarajan, Sanjay and Blake, Gerard and Sarin, Parth and Buttrick, Adam and Patel, Bhavesh},
211
  year = {2026},
212
+ version = {1.4.0},
213
  url = {https://huggingface.co/fairdataihub/poster-sentry},
214
  note = {Part of the posters.science initiative}
215
  }
config.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "model_type": "poster-sentry",
3
- "version": "1.3.0",
4
  "architecture": "stacked_logistic_regression_multimodal",
5
  "embedding_backbone": "minishlab/potion-base-32M",
6
  "embedding_dim": 512,
@@ -15,17 +15,18 @@
15
  "head_file": "models/poster_sentry_head.npz",
16
  "scaler": "StandardScaler",
17
  "classifier": "LogisticRegression",
18
- "accuracy": 0.9313,
19
  "accuracy_ci95": [
20
- 0.9055,
21
- 0.9504
22
  ],
23
- "oof_accuracy": 0.9391,
24
- "training_samples": 3298,
25
  "label_provenance": "human-validated (three-reviewer survey with blinded adjudication)",
26
  "library_name": "model2vec",
27
  "pdf_backend": "pdfplumber + pypdfium2",
28
  "stage1": "LogisticRegression over the 512-d text embedding; poster probability becomes the text_score feature",
29
  "final_classifier_features": 31,
30
- "corpus_poster_pct": 80.5
31
- }
 
 
1
  {
2
  "model_type": "poster-sentry",
3
+ "version": "1.4.0",
4
  "architecture": "stacked_logistic_regression_multimodal",
5
  "embedding_backbone": "minishlab/potion-base-32M",
6
  "embedding_dim": 512,
 
15
  "head_file": "models/poster_sentry_head.npz",
16
  "scaler": "StandardScaler",
17
  "classifier": "LogisticRegression",
18
+ "accuracy": 0.9444,
19
  "accuracy_ci95": [
20
+ 0.9204,
21
+ 0.9615
22
  ],
23
+ "oof_accuracy": 0.944,
24
+ "training_samples": 3235,
25
  "label_provenance": "human-validated (three-reviewer survey with blinded adjudication)",
26
  "library_name": "model2vec",
27
  "pdf_backend": "pdfplumber + pypdfium2",
28
  "stage1": "LogisticRegression over the 512-d text embedding; poster probability becomes the text_score feature",
29
  "final_classifier_features": 31,
30
+ "corpus_poster_pct": 80.4,
31
+ "text_extraction": "poster2json layout engine on pdfplumber (first page), pdfplumber default when it returns no text"
32
+ }
models/poster_sentry_head.npz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d23af6c5235bff4e1521261fc615933c119880c6cd13f46fa53d30af69d832d7
3
  size 20002
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f02b7d83c710c7cf759d593d47ac2f35f822dcbf691448d43c8dff97ee550dc9
3
  size 20002
pyproject.toml CHANGED
@@ -4,32 +4,77 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "poster-sentry"
7
- version = "0.1.0"
8
- description = "Multimodal scientific poster classifier — text + visual features"
9
  readme = "README.md"
10
  license = {text = "MIT"}
11
  requires-python = ">=3.10"
12
  authors = [
13
- {name = "Jamey O'Neill", email = "joneill@calmi2.org"},
 
 
 
 
 
14
  {name = "FAIR Data Innovations Hub", email = "info@fairdataihub.org"},
15
  ]
16
- keywords = ["scientific-posters", "classification", "multimodal", "document-classification"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  dependencies = [
19
  "numpy>=1.24",
20
  "model2vec>=0.3.0",
21
  "scikit-learn>=1.3",
22
- "PyMuPDF>=1.23.0",
 
23
  "Pillow>=10.0.0",
24
  ]
25
 
26
  [project.optional-dependencies]
27
- train = [
 
28
  "tqdm>=4.65",
29
  ]
 
 
 
 
 
30
 
31
  [project.scripts]
32
  poster-sentry = "poster_sentry.cli:main"
33
 
 
 
 
 
 
 
 
34
  [tool.setuptools.packages.find]
35
  where = ["src"]
 
 
 
 
 
 
 
 
4
 
5
  [project]
6
  name = "poster-sentry"
7
+ version = "0.3.0"
8
+ description = "Lightweight multimodal scientific poster classifier — text + visual + structural features"
9
  readme = "README.md"
10
  license = {text = "MIT"}
11
  requires-python = ">=3.10"
12
  authors = [
13
+ {name = "James O'Neill", email = "joneill@calmi2.org"},
14
+ {name = "Sanjay Soundarajan"},
15
+ {name = "Dorian Portillo"},
16
+ {name = "Bhavesh Patel", email = "bpatel@calmi2.org"},
17
+ ]
18
+ maintainers = [
19
  {name = "FAIR Data Innovations Hub", email = "info@fairdataihub.org"},
20
  ]
21
+ keywords = [
22
+ "scientific-posters",
23
+ "classification",
24
+ "multimodal",
25
+ "document-classification",
26
+ "quality-control",
27
+ "FAIR-data",
28
+ "posters-science",
29
+ ]
30
+ classifiers = [
31
+ "Development Status :: 4 - Beta",
32
+ "Intended Audience :: Science/Research",
33
+ "License :: OSI Approved :: MIT License",
34
+ "Programming Language :: Python :: 3",
35
+ "Programming Language :: Python :: 3.10",
36
+ "Programming Language :: Python :: 3.11",
37
+ "Programming Language :: Python :: 3.12",
38
+ "Topic :: Scientific/Engineering",
39
+ "Topic :: Text Processing :: General",
40
+ ]
41
 
42
  dependencies = [
43
  "numpy>=1.24",
44
  "model2vec>=0.3.0",
45
  "scikit-learn>=1.3",
46
+ "pdfplumber>=0.11.0",
47
+ "pypdfium2>=4.0.0",
48
  "Pillow>=10.0.0",
49
  ]
50
 
51
  [project.optional-dependencies]
52
+ dev = [
53
+ "pytest>=7.0",
54
  "tqdm>=4.65",
55
  ]
56
+ # Optional faster PDF backend. PyMuPDF is AGPL-licensed, so it is not a default
57
+ # dependency; the released model is trained on the default pdfplumber backend.
58
+ pymupdf = [
59
+ "PyMuPDF>=1.23.0",
60
+ ]
61
 
62
  [project.scripts]
63
  poster-sentry = "poster_sentry.cli:main"
64
 
65
+ [project.urls]
66
+ Homepage = "https://posters.science"
67
+ Repository = "https://github.com/fairdataihub/poster-sentry"
68
+ "HuggingFace Model" = "https://huggingface.co/fairdataihub/poster-sentry"
69
+ "Training Data" = "https://huggingface.co/datasets/fairdataihub/poster-sentry-training-data"
70
+ "Bug Tracker" = "https://github.com/fairdataihub/poster-sentry/issues"
71
+
72
  [tool.setuptools.packages.find]
73
  where = ["src"]
74
+ include = ["poster_sentry*"]
75
+
76
+ [tool.setuptools.package-data]
77
+ poster_sentry = ["../models/*.npz"]
78
+
79
+ [tool.pytest.ini_options]
80
+ testpaths = ["tests"]
scripts/train_poster_sentry.py CHANGED
@@ -1,402 +1,194 @@
1
  #!/usr/bin/env python3
2
- """
3
- Train PosterSentry on the real posters.science corpus.
4
-
5
- Data sources (all real, zero synthetic):
6
- Positive (poster):
7
- 28K+ verified scientific posters from Zenodo & Figshare
8
- /home/joneill/Nextcloud/vaults/jmind/calmi2/poster_science/poster-pdf-meta/downloads/
9
-
10
- Negative (non_poster):
11
- 2,036 verified non-posters (multi-page docs, proceedings, abstracts)
12
- Listed in: poster_classifier/non_posters_20251208_152217.txt
13
-
14
- Plus: single pages extracted from armanc/scientific_papers (real papers)
15
- Plus: ag_news articles (real junk text, rendered to match)
16
-
17
- Usage:
18
- cd /home/joneill/pubverse_brett/poster_sentry
19
- pip install -e ".[train]"
20
- python scripts/train_poster_sentry.py --n-per-class 5000
21
- """
22
-
23
- import argparse
24
- import json
25
- import logging
26
- import os
27
- import random
28
- import sys
29
- import time
30
  from pathlib import Path
31
- from typing import Dict, List, Optional, Tuple
32
-
33
  import numpy as np
34
 
35
- logging.basicConfig(
36
- level=logging.INFO,
37
- format="%(asctime)s | %(levelname)s | %(message)s",
38
- datefmt="%Y-%m-%d %H:%M:%S",
39
- )
40
- logger = logging.getLogger(__name__)
41
-
42
  SEED = 42
43
- random.seed(SEED)
44
  np.random.seed(SEED)
45
 
46
- # ── Paths ────────────────────────────────────────────────────────
47
-
48
- POSTER_SCIENCE_BASE = Path(
49
- "/home/joneill/Nextcloud/vaults/jmind/calmi2/poster_science"
50
- )
51
- DOWNLOADS_DIR = POSTER_SCIENCE_BASE / "poster-pdf-meta" / "downloads"
52
- NON_POSTERS_LIST = (
53
- POSTER_SCIENCE_BASE
54
- / "poster_classifier"
55
- / "non_posters_20251208_152217.txt"
56
- )
57
- CLASSIFICATION_JSON = (
58
- POSTER_SCIENCE_BASE
59
- / "poster_classifier"
60
- / "classification_results_20251208_152217.json"
61
- )
62
-
63
-
64
- def _fix_path(p: str) -> str:
65
- """Fix paths from classification JSON — they use /home/joneill/vaults/
66
- but the actual Nextcloud mount is /home/joneill/Nextcloud/vaults/."""
67
- if "/joneill/vaults/" in p and "/Nextcloud/" not in p:
68
- return p.replace("/joneill/vaults/", "/joneill/Nextcloud/vaults/")
69
- return p
70
-
71
-
72
- def collect_poster_paths(max_n: int = 10000) -> List[str]:
73
- """Collect verified poster PDF paths from the corpus."""
74
- # Load the classification results to get confirmed poster paths
75
- if CLASSIFICATION_JSON.exists():
76
- logger.info(f"Loading classification results from {CLASSIFICATION_JSON}")
77
- with open(CLASSIFICATION_JSON) as f:
78
- data = json.load(f)
79
- poster_entries = data.get("posters", [])
80
- paths = [_fix_path(e["pdf_path"]) for e in poster_entries if Path(_fix_path(e["pdf_path"])).exists()]
81
- logger.info(f" Found {len(paths)} verified poster paths")
82
- else:
83
- # Fallback: glob the downloads directory
84
- logger.info(f"Globbing {DOWNLOADS_DIR} for PDFs...")
85
- paths = [str(p) for p in DOWNLOADS_DIR.rglob("*.pdf")]
86
- paths += [str(p) for p in DOWNLOADS_DIR.rglob("*.PDF")]
87
- logger.info(f" Found {len(paths)} PDFs")
88
-
89
- random.shuffle(paths)
90
- return paths[:max_n]
91
-
92
-
93
- def collect_non_poster_paths(max_n: int = 2000) -> List[str]:
94
- """Collect verified non-poster PDF paths.
95
-
96
- The non-posters were separated into:
97
- poster-pdf-meta/separated_non_posters/downloads/{zenodo,figshare}/
98
- """
99
- paths = []
100
-
101
- # Primary: glob the separated_non_posters directory
102
- sep_dir = POSTER_SCIENCE_BASE / "poster-pdf-meta" / "separated_non_posters" / "downloads"
103
- if sep_dir.exists():
104
- for pdf in sep_dir.rglob("*.pdf"):
105
- paths.append(str(pdf))
106
- for pdf in sep_dir.rglob("*.PDF"):
107
- paths.append(str(pdf))
108
- logger.info(f" Found {len(paths)} non-poster PDFs in {sep_dir}")
109
- else:
110
- # Fallback: try the original list with path fixing
111
- logger.info(" Separated dir not found, trying original list...")
112
- if NON_POSTERS_LIST.exists():
113
- with open(NON_POSTERS_LIST) as f:
114
- for line in f:
115
- p = _fix_path(line.strip())
116
- if p and Path(p).exists():
117
- paths.append(p)
118
- logger.info(f" Found {len(paths)} verified non-poster paths from list")
119
-
120
- random.shuffle(paths)
121
- return paths[:max_n]
122
-
123
-
124
- def extract_features_from_pdfs(
125
- pdf_paths: List[str],
126
- label: int,
127
- text_model,
128
- visual_ext,
129
- structural_ext,
130
- max_text_chars: int = 4000,
131
- ) -> Tuple[np.ndarray, np.ndarray, List[str]]:
132
- """
133
- Extract multimodal features from a list of PDFs.
134
-
135
- Returns (X, y, extracted_texts) where:
136
- X: (N, 542) feature matrix
137
- y: (N,) labels
138
- extracted_texts: list of extracted text strings (for PubGuard reuse)
139
- """
140
- from tqdm import tqdm
141
- import fitz
142
- import re
143
-
144
- embeddings = []
145
- visual_vecs = []
146
- struct_vecs = []
147
- texts_out = []
148
- labels = []
149
-
150
- for pdf_path in tqdm(pdf_paths, desc=f"{'poster' if label == 1 else 'non_poster'}"):
151
- try:
152
- # Extract text
153
- doc = fitz.open(pdf_path)
154
- if len(doc) == 0:
155
- doc.close()
156
- continue
157
- text = doc[0].get_text()
158
- doc.close()
159
- text = re.sub(r"\s+", " ", text).strip()[:max_text_chars]
160
-
161
- if len(text) < 20:
162
- continue
163
-
164
- # Visual features
165
- img = visual_ext.pdf_to_image(pdf_path)
166
- if img is not None:
167
- vf = visual_ext.extract(img)
168
- else:
169
- vf = {n: 0.0 for n in visual_ext.FEATURE_NAMES}
170
-
171
- # Structural features
172
- sf = structural_ext.extract(pdf_path)
173
-
174
- texts_out.append(text)
175
- visual_vecs.append(visual_ext.to_vector(vf))
176
- struct_vecs.append(structural_ext.to_vector(sf))
177
- labels.append(label)
178
-
179
- except Exception as e:
180
- logger.debug(f"Skipping {pdf_path}: {e}")
181
- continue
182
-
183
- if not texts_out:
184
- return np.array([]), np.array([]), []
185
-
186
- # Embed all texts at once
187
- logger.info(f"Embedding {len(texts_out)} texts...")
188
- emb = text_model.encode(texts_out, show_progress_bar=True)
189
- norms = np.linalg.norm(emb, axis=1, keepdims=True)
190
- norms = np.where(norms == 0, 1, norms)
191
- emb = (emb / norms).astype("float32")
192
-
193
- visual_arr = np.array(visual_vecs, dtype="float32")
194
- struct_arr = np.array(struct_vecs, dtype="float32")
195
-
196
- X = np.concatenate([emb, visual_arr, struct_arr], axis=1)
197
- y = np.array(labels)
198
-
199
- return X, y, texts_out
200
-
201
-
202
- def main():
203
- parser = argparse.ArgumentParser(description="Train PosterSentry")
204
- parser.add_argument("--n-per-class", type=int, default=5000,
205
- help="Max samples per class (poster/non_poster)")
206
- parser.add_argument("--test-size", type=float, default=0.15)
207
- parser.add_argument("--models-dir", default=None)
208
- parser.add_argument("--export-texts", default=None,
209
- help="Export extracted texts as NDJSON for PubGuard retraining")
210
- args = parser.parse_args()
211
-
212
- from model2vec import StaticModel
213
- from sklearn.linear_model import LogisticRegression
214
- from sklearn.metrics import classification_report
215
- from sklearn.model_selection import train_test_split
216
- from poster_sentry.features import VisualFeatureExtractor, PDFStructuralExtractor
217
-
218
- # Models dir
219
- if args.models_dir:
220
- models_dir = Path(args.models_dir)
221
- else:
222
- models_dir = Path.home() / ".poster_sentry" / "models"
223
- models_dir.mkdir(parents=True, exist_ok=True)
224
-
225
- # Load embedding model
226
- logger.info("Loading model2vec...")
227
- emb_cache = models_dir / "poster-sentry-embedding"
228
- if emb_cache.exists():
229
- text_model = StaticModel.from_pretrained(str(emb_cache))
230
- else:
231
- text_model = StaticModel.from_pretrained("minishlab/potion-base-32M")
232
- emb_cache.parent.mkdir(parents=True, exist_ok=True)
233
- text_model.save_pretrained(str(emb_cache))
234
-
235
- visual_ext = VisualFeatureExtractor()
236
- structural_ext = PDFStructuralExtractor()
237
-
238
- # ── Collect data ─────────────────────────────────────────────
239
- logger.info("=" * 60)
240
- logger.info("Collecting training data...")
241
- logger.info("=" * 60)
242
-
243
- poster_paths = collect_poster_paths(max_n=args.n_per_class)
244
- non_poster_paths = collect_non_poster_paths(max_n=args.n_per_class)
245
-
246
- logger.info(f"Poster PDFs to process: {len(poster_paths)}")
247
- logger.info(f"Non-poster PDFs to process: {len(non_poster_paths)}")
248
-
249
- # ── Extract features ─────────────────────────────────────────
250
- logger.info("=" * 60)
251
- logger.info("Extracting features from poster PDFs...")
252
- logger.info("=" * 60)
253
-
254
- X_pos, y_pos, texts_pos = extract_features_from_pdfs(
255
- poster_paths, label=1, text_model=text_model,
256
- visual_ext=visual_ext, structural_ext=structural_ext,
257
- )
258
-
259
- logger.info(f"Poster features: {X_pos.shape}")
260
-
261
- logger.info("=" * 60)
262
- logger.info("Extracting features from non-poster PDFs...")
263
- logger.info("=" * 60)
264
-
265
- X_neg, y_neg, texts_neg = extract_features_from_pdfs(
266
- non_poster_paths, label=0, text_model=text_model,
267
- visual_ext=visual_ext, structural_ext=structural_ext,
268
- )
269
-
270
- logger.info(f"Non-poster features: {X_neg.shape}")
271
-
272
- # ── Balance classes ──────────────────────────────────────────
273
- min_count = min(len(y_pos), len(y_neg))
274
- logger.info(f"Balancing: {min_count} samples per class")
275
-
276
- if len(y_pos) > min_count:
277
- idx = np.random.choice(len(y_pos), min_count, replace=False)
278
- X_pos = X_pos[idx]
279
- y_pos = y_pos[idx]
280
- texts_pos = [texts_pos[i] for i in idx]
281
-
282
- if len(y_neg) > min_count:
283
- idx = np.random.choice(len(y_neg), min_count, replace=False)
284
- X_neg = X_neg[idx]
285
- y_neg = y_neg[idx]
286
- texts_neg = [texts_neg[i] for i in idx]
287
-
288
- X = np.vstack([X_pos, X_neg])
289
- y = np.concatenate([y_pos, y_neg])
290
-
291
- logger.info(f"Total training data: {X.shape} (poster={sum(y)}, non_poster={len(y)-sum(y)})")
292
-
293
- # ── Export texts for PubGuard ────────────────────────────────
294
- if args.export_texts:
295
- export_path = Path(args.export_texts)
296
- export_path.parent.mkdir(parents=True, exist_ok=True)
297
- with open(export_path, "w") as f:
298
- for text in texts_pos:
299
- f.write(json.dumps({"text": text, "label": "poster"}) + "\n")
300
- for text in texts_neg:
301
- f.write(json.dumps({"text": text, "label": "non_poster"}) + "\n")
302
- logger.info(f"Exported {len(texts_pos) + len(texts_neg)} texts to {export_path}")
303
-
304
- # ── Feature scaling ──────────────────────────────────────────
305
- # Critical: the 512-d text embedding drowns out the 30 structural/visual
306
- # features if we don't scale. StandardScaler normalizes each column to
307
- # zero mean and unit variance, giving structural signals fair weight.
308
- from sklearn.preprocessing import StandardScaler
309
-
310
- logger.info("=" * 60)
311
- logger.info("Scaling features (StandardScaler)")
312
- logger.info("=" * 60)
313
-
314
- scaler = StandardScaler()
315
- X_scaled = scaler.fit_transform(X)
316
-
317
- # Log feature variance to confirm structural features are alive
318
- emb_var = np.mean(np.var(X_scaled[:, :512], axis=0))
319
- vis_var = np.mean(np.var(X_scaled[:, 512:527], axis=0))
320
- str_var = np.mean(np.var(X_scaled[:, 527:], axis=0))
321
- logger.info(f" Mean variance — text: {emb_var:.3f} visual: {vis_var:.3f} structural: {str_var:.3f}")
322
-
323
- # ── Train ────────────────────────────────────────────────────
324
- logger.info("=" * 60)
325
- logger.info("Training PosterSentry classifier")
326
- logger.info("=" * 60)
327
-
328
- X_tr, X_te, y_tr, y_te = train_test_split(
329
- X_scaled, y, test_size=args.test_size, stratify=y, random_state=SEED,
330
- )
331
-
332
- logger.info(f"Train: {X_tr.shape[0]:,} | Test: {X_te.shape[0]:,}")
333
- logger.info(f"Features: {X_tr.shape[1]} (512 text + 15 visual + 15 structural)")
334
-
335
- clf = LogisticRegression(
336
- C=1.0, max_iter=1000, class_weight="balanced",
337
- solver="lbfgs", n_jobs=1, random_state=SEED,
338
- )
339
-
340
- t0 = time.time()
341
- clf.fit(X_tr, y_tr)
342
- elapsed = time.time() - t0
343
- logger.info(f"Trained in {elapsed:.1f}s")
344
-
345
- y_pred = clf.predict(X_te)
346
- labels = ["non_poster", "poster"]
347
- report = classification_report(y_te, y_pred, target_names=labels, digits=4)
348
- logger.info(f"\n{report}")
349
-
350
- # Show top feature importances
351
- coef = clf.coef_[0]
352
- all_names = (
353
- [f"emb_{i}" for i in range(512)]
354
- + list(VisualFeatureExtractor.FEATURE_NAMES)
355
- + list(PDFStructuralExtractor.FEATURE_NAMES)
356
- )
357
- top_idx = np.argsort(np.abs(coef))[-15:][::-1]
358
- logger.info("Top 15 features by |coefficient|:")
359
- for idx in top_idx:
360
- logger.info(f" {all_names[idx]:30s} coef={coef[idx]:+.4f}")
361
-
362
- # ── Save head as .npz ────────────────────────────────────────
363
- if clf.coef_.shape[0] == 1:
364
- W = np.vstack([-clf.coef_[0], clf.coef_[0]]).T.astype("float32")
365
- b = np.array([-clf.intercept_[0], clf.intercept_[0]], dtype="float32")
366
- else:
367
- W = clf.coef_.T.astype("float32")
368
- b = clf.intercept_.astype("float32")
369
-
370
- head_path = models_dir / "poster_sentry_head.npz"
371
- np.savez(
372
- head_path, W=W, b=b, labels=np.array(labels),
373
- scaler_mean=scaler.mean_.astype("float32"),
374
- scaler_scale=scaler.scale_.astype("float32"),
375
- )
376
- logger.info(f"Saved classifier head + scaler → {head_path}")
377
-
378
- # ── Smoke test ───────────────────────────────────────────────
379
- logger.info("\n" + "=" * 60)
380
- logger.info("SMOKE TEST")
381
- logger.info("=" * 60)
382
-
383
- from poster_sentry import PosterSentry
384
-
385
- sentry = PosterSentry(models_dir=models_dir)
386
- sentry.initialize()
387
-
388
- # Test with some real PDFs
389
- test_pdfs = poster_paths[:2] + non_poster_paths[:2]
390
- for p in test_pdfs:
391
- try:
392
- result = sentry.classify(p)
393
- icon = "📋" if result["is_poster"] else "📄"
394
- print(f" {icon} {Path(p).name[:60]:60s} poster={result['is_poster']} conf={result['confidence']:.3f}")
395
- except Exception as e:
396
- print(f" ⚠️ {Path(p).name[:60]}: {e}")
397
-
398
- logger.info(f"\nDone! Model saved to: {models_dir}")
399
-
400
-
401
- if __name__ == "__main__":
402
- main()
 
1
  #!/usr/bin/env python3
2
+ # Train PosterSentry on the human-validated survey corpus: 3,414 documents, each released by
3
+ # its depositor under CC0, CC-BY, or an equivalent permissive license (2,994 rated unanimously,
4
+ # 420 settled in the blinded adjudication). The training corpus is the 3,235 documents listed in
5
+ # data/poster_sentry_train.ndjson, in that order (near-duplicates and documents without a usable
6
+ # PDF were removed beforehand, as recorded in final_labels.csv of the Zenodo record).
7
+ import csv, json, os, re, sys, time
8
+ from collections import Counter, defaultdict
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  from pathlib import Path
 
 
10
  import numpy as np
11
 
12
+ sys.path.insert(0, os.environ.get("POSTERSENTRY_PKG", "/home/joneill/Nextcloud/vaults/jmind/calmi2/poster-sentry"))
 
 
 
 
 
 
13
  SEED = 42
 
14
  np.random.seed(SEED)
15
 
16
+ # survey inputs: the inputs/ folder of poster-sentry-evaluation-paper-code
17
+ A = os.environ.get("POSTERSENTRY_INPUTS", "/home/joneill/wt-postersentry-eval/inputs")
18
+ ADJ = f"{A}/postersentry_adjudication_2026-08-16.csv"
19
+ TRAIN = Path(__file__).resolve().parent.parent / "data" / "poster_sentry_train.ndjson"
20
+ ROOT = Path("/home/joneill/Nextcloud/vaults/jmind/calmi2/poster_science/poster-pdf-meta")
21
+ OUT = Path(os.environ.get("POSTERSENTRY_OUT", "/mnt/fast/postersentry/ccby_2026-10-28/training_repo_run"))
22
+ OUT.mkdir(parents=True, exist_ok=True)
23
+
24
+ PANEL = ["cpc1efk8xl7ogclt0i3zeu3o", "j32isol0qqy827448hqci1dd", "u4v0dvvfdss6i2wfkc7exa12"]
25
+
26
+ # ---------- 1. human-validated labels ----------
27
+ votes = defaultdict(dict)
28
+ for r in csv.DictReader(open(f"{A}/evaluations_2026-08-02.csv")):
29
+ if r["userId"] in PANEL:
30
+ votes[r["posterId"]][r["userId"]] = r["userChoice"].replace("-", "_").strip()
31
+
32
+ adj = {r["posterId"]: r["decision"] for r in csv.DictReader(open(ADJ))}
33
+
34
+ meta = {r["id"]: r["originalFilename"] for r in csv.DictReader(open(f"{A}/posters_2026-08-02.csv"))}
35
+
36
+ labels = {}
37
+ n_unan = 0
38
+ for pid, v in votes.items():
39
+ if pid in adj:
40
+ labels[pid] = adj[pid]
41
+ continue
42
+ c = Counter(x for x in v.values() if x != "unsure")
43
+ assert c and min(c.get("poster", 0), c.get("non_poster", 0)) == 0, f"non-unanimous outside adjudication: {pid}"
44
+ labels[pid] = "poster" if c.get("poster", 0) > 0 else "non_poster"
45
+ n_unan += 1
46
+ bal = Counter(labels.values())
47
+ print(f"labels: {len(labels)} total | unanimous {n_unan} | adjudicated {len(adj)}")
48
+ print(f"class balance: {dict(bal)}")
49
+
50
+ # ---------- 2. resolve PDF paths ----------
51
+ def resolve(fn):
52
+ stem = re.sub(r"^\d+_", "", fn)
53
+ stem = re.sub(r"\.jpg$", "", stem, flags=re.I)
54
+ source = "zenodo" if stem.startswith("zenodo_") else "figshare"
55
+ for base in (ROOT / "downloads" / source, ROOT / "separated_non_posters" / "downloads" / source):
56
+ p = base / f"{stem}.pdf"
57
+ if p.exists():
58
+ return str(p)
59
+ return None
60
+
61
+ train_rows = [json.loads(l) for l in open(TRAIN)]
62
+ assert all(labels[r["id"]] == r["label"] for r in train_rows), "labels disagree with the released training corpus"
63
+ order = [r["id"] for r in train_rows]
64
+ print(f"training corpus: {len(order)} documents")
65
+
66
+ paths, missing = {}, []
67
+ for pid in order:
68
+ p = resolve(meta[pid])
69
+ if p: paths[pid] = p
70
+ else: missing.append(meta[pid])
71
+ print(f"paths resolved: {len(paths)} | missing: {len(missing)}")
72
+ for m in missing[:8]: print(" missing:", m)
73
+
74
+ # ---------- 3. feature extraction (parallel) ----------
75
+ from poster_sentry.features import VisualFeatureExtractor, PDFStructuralExtractor
76
+
77
+ def work(item):
78
+ pid, path = item
79
+ from poster_sentry.features import VisualFeatureExtractor as V, PDFStructuralExtractor as S, extract_first_page_text
80
+ v = V(); s = S()
81
+ try:
82
+ # first-page text from the poster2json layout engine (pdfplumber default when it returns no text),
83
+ # whitespace-normalized and truncated to 4,000 characters
84
+ text = extract_first_page_text(path)
85
+ img = v.pdf_to_image(path)
86
+ vf = v.extract(img) if img is not None else {n: 0.0 for n in v.FEATURE_NAMES}
87
+ sf = s.extract(path)
88
+ return (pid, text, v.to_vector(vf), s.to_vector(sf))
89
+ except Exception:
90
+ return None
91
+
92
+ t0 = time.time()
93
+ from multiprocessing import Pool
94
+ with Pool(12) as pool:
95
+ results = [r for r in pool.imap_unordered(work, list(paths.items()), chunksize=25) if r is not None]
96
+ print(f"extracted: {len(results)} of {len(paths)} in {time.time()-t0:.0f}s")
97
+
98
+ # ---------- 4. rows in the released training order (the seed-42 split depends on it) ----------
99
+ got = {r[0]: r for r in results}
100
+ assert len(got) == len(order), f"feature extraction failed for {len(order) - len(got)} documents"
101
+ dedup = [got[pid] for pid in order]
102
+ short, dropped = 0, 0
103
+
104
+ ids = [r[0] for r in dedup]
105
+ texts = [r[1] for r in dedup]
106
+ y = np.array([1 if labels[i] == "poster" else 0 for i in ids])
107
+ print(f"final label balance: poster={int(y.sum())} non_poster={int((1-y).sum())}")
108
+
109
+ from model2vec import StaticModel
110
+ tm = StaticModel.from_pretrained("minishlab/potion-base-32M")
111
+ emb = tm.encode(texts)
112
+ nrm = np.linalg.norm(emb, axis=1, keepdims=True); nrm = np.where(nrm == 0, 1, nrm)
113
+ emb = (emb / nrm).astype("float32")
114
+ X = np.concatenate([emb, np.array([r[2] for r in dedup], dtype="float32"),
115
+ np.array([r[3] for r in dedup], dtype="float32")], axis=1)
116
+ print(f"feature matrix: {X.shape}")
117
+
118
+ # ---------- 5. split, scale, train (stacked) ----------
119
+ from sklearn.model_selection import train_test_split, StratifiedKFold
120
+ from sklearn.preprocessing import StandardScaler
121
+ from sklearn.linear_model import LogisticRegression
122
+ from sklearn.metrics import classification_report, accuracy_score
123
+
124
+ X = X.astype("float64")
125
+ Xt, Xe = X[:, :512], X[:, 512:]
126
+ LRM = lambda: LogisticRegression(C=1.0, max_iter=1000, class_weight="balanced",
127
+ solver="lbfgs", n_jobs=1, random_state=SEED)
128
+
129
+ # Stacked architecture: stage 1 scores the 512-d text embedding alone; its
130
+ # poster probability becomes the single text_score feature of stage 2, which
131
+ # classifies [text_score + 15 visual + 15 structural] = 31 features. Stage 2
132
+ # trains on inner 5-fold out-of-fold text scores so it never sees an
133
+ # in-sample-optimistic text score (leak-free stacking).
134
+ def text_oof_scores(T, yy):
135
+ out = np.zeros(len(yy))
136
+ for trn, val in StratifiedKFold(5, shuffle=True, random_state=SEED).split(T, yy):
137
+ s = StandardScaler().fit(T[trn]); c = LRM(); c.fit(s.transform(T[trn]), yy[trn])
138
+ out[val] = c.predict_proba(s.transform(T[val]))[:, 1]
139
+ return out
140
+
141
+ idx = np.arange(len(y))
142
+ tr, te = train_test_split(idx, test_size=0.15, stratify=y, random_state=SEED)
143
+ print(f"train {len(tr)} | test {len(te)} (test balance: poster={int(y[te].sum())}, non={int((1-y[te]).sum())})")
144
+
145
+ s1 = StandardScaler().fit(Xt[tr]); c1 = LRM(); c1.fit(s1.transform(Xt[tr]), y[tr])
146
+ ts_tr = text_oof_scores(Xt[tr], y[tr])
147
+ S_tr = np.column_stack([ts_tr, Xe[tr]])
148
+ s2 = StandardScaler().fit(S_tr); c2 = LRM(); c2.fit(s2.transform(S_tr), y[tr])
149
+
150
+ ts_te = c1.predict_proba(s1.transform(Xt[te]))[:, 1]
151
+ S_te = np.column_stack([ts_te, Xe[te]])
152
+ pred = c2.predict(s2.transform(S_te))
153
+ print(classification_report(y[te], pred, target_names=["non_poster", "poster"], digits=4))
154
+ acc = accuracy_score(y[te], pred)
155
+
156
+ # ---------- 6. top features + save ----------
157
+ names31 = (["text_score"] + list(VisualFeatureExtractor.FEATURE_NAMES)
158
+ + list(PDFStructuralExtractor.FEATURE_NAMES))
159
+ coef = c2.coef_[0]
160
+ top = np.argsort(np.abs(coef))[-15:][::-1]
161
+ print("\nTop 15 stage-2 features:")
162
+ for i in top: print(f" {names31[i]:24s} {coef[i]:+.3f}")
163
+
164
+ # Zero first column so that softmax over the two columns reproduces sklearn's
165
+ # sigmoid exactly (a [-c, +c] convention would double the logit and sharpen
166
+ # probabilities; harmless for a 0.5 decision, wrong for a stacked feature).
167
+ def two_col(clf):
168
+ W = np.vstack([np.zeros_like(clf.coef_[0]), clf.coef_[0]]).T.astype("float64")
169
+ b = np.array([0.0, clf.intercept_[0]], dtype="float64")
170
+ return W, b
171
+ W1, b1 = two_col(c1); W2, b2 = two_col(c2)
172
+ # The released head is the same recipe refit on the full corpus.
173
+ s1 = StandardScaler().fit(Xt); c1 = LRM(); c1.fit(s1.transform(Xt), y)
174
+ S_all = np.column_stack([text_oof_scores(Xt, y), Xe])
175
+ s2 = StandardScaler().fit(S_all); c2 = LRM(); c2.fit(s2.transform(S_all), y)
176
+ W1, b1 = two_col(c1); W2, b2 = two_col(c2)
177
+ coef = c2.coef_[0]; top = np.argsort(np.abs(coef))[-15:][::-1]
178
+ np.savez(OUT / "poster_sentry_head.npz", arch=np.array("stacked"),
179
+ labels=np.array(["non_poster", "poster"]),
180
+ W=W2, b=b2, scaler_mean=s2.mean_, scaler_scale=s2.scale_,
181
+ s1_W=W1, s1_b=b1, s1_scaler_mean=s1.mean_, s1_scaler_scale=s1.scale_)
182
+ np.savez(OUT / "features_cache.npz", X=X.astype("float32"), y=y, ids=np.array(ids))
183
+ json.dump({
184
+ "date": "2026-10-28", "seed": SEED, "arch": "stacked",
185
+ "labels_total": len(labels), "unanimous": n_unan, "adjudicated": len(adj),
186
+ "class_balance": dict(bal), "paths_resolved": len(paths), "extract_failures": len(paths) - len(results),
187
+ "short_text_dropped": short, "near_duplicates_removed": dropped,
188
+ "final_corpus": len(dedup), "final_poster": int(y.sum()), "final_non_poster": int((1 - y).sum()),
189
+ "train": len(tr), "test": len(te),
190
+ "test_accuracy": acc,
191
+ "top15_stage2": [[names31[i], float(coef[i])] for i in top],
192
+ }, open(OUT / "metrics.json", "w"), indent=1)
193
+ print(f"\nSaved head + features + metrics to {OUT}")
194
+ print(f"SUMMARY: held-out={acc:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/poster_sentry/__init__.py CHANGED
@@ -20,5 +20,5 @@ Usage:
20
  from .classifier import PosterSentry
21
  from .features import VisualFeatureExtractor, PDFStructuralExtractor
22
 
23
- __version__ = "0.1.0"
24
  __all__ = ["PosterSentry", "VisualFeatureExtractor", "PDFStructuralExtractor"]
 
20
  from .classifier import PosterSentry
21
  from .features import VisualFeatureExtractor, PDFStructuralExtractor
22
 
23
+ __version__ = "0.3.0"
24
  __all__ = ["PosterSentry", "VisualFeatureExtractor", "PDFStructuralExtractor"]
src/poster_sentry/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Allow running PosterSentry as ``python -m poster_sentry``."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
src/poster_sentry/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.03 kB). View file
 
src/poster_sentry/__pycache__/classifier.cpython-312.pyc ADDED
Binary file (15.9 kB). View file
 
src/poster_sentry/__pycache__/cli.cpython-312.pyc ADDED
Binary file (5.42 kB). View file
 
src/poster_sentry/__pycache__/features.cpython-312.pyc ADDED
Binary file (22.3 kB). View file
 
src/poster_sentry/classifier.py CHANGED
@@ -55,11 +55,17 @@ class PosterSentry:
55
  self,
56
  model_name: str = "minishlab/potion-base-32M",
57
  models_dir: Optional[Path] = None,
 
58
  ):
59
  self.model_name = model_name
60
  self.models_dir = models_dir or self._default_models_dir()
61
  self.models_dir = Path(self.models_dir)
62
 
 
 
 
 
 
63
  self.text_model = None
64
  self.W: Optional[np.ndarray] = None
65
  self.b: Optional[np.ndarray] = None
@@ -67,8 +73,19 @@ class PosterSentry:
67
  self.scaler_scale: Optional[np.ndarray] = None
68
  self.labels = ["non_poster", "poster"]
69
 
70
- self.visual_extractor = VisualFeatureExtractor()
71
- self.structural_extractor = PDFStructuralExtractor()
 
 
 
 
 
 
 
 
 
 
 
72
  self._initialized = False
73
 
74
  @staticmethod
@@ -76,6 +93,11 @@ class PosterSentry:
76
  import os
77
  if env := os.environ.get("POSTER_SENTRY_MODELS_DIR"):
78
  return Path(env)
 
 
 
 
 
79
  home = Path.home() / ".poster_sentry" / "models"
80
  home.mkdir(parents=True, exist_ok=True)
81
  return home
@@ -107,6 +129,7 @@ class PosterSentry:
107
  path = self.models_dir / "poster_sentry_head.npz"
108
  if path.exists():
109
  data = np.load(path, allow_pickle=True)
 
110
  self.W = data["W"]
111
  self.b = data["b"]
112
  if "labels" in data:
@@ -114,33 +137,34 @@ class PosterSentry:
114
  if "scaler_mean" in data and "scaler_scale" in data:
115
  self.scaler_mean = data["scaler_mean"]
116
  self.scaler_scale = data["scaler_scale"]
117
- logger.info(f" Loaded classifier head: {path}")
 
 
 
 
 
118
  else:
119
  logger.warning(f" Head not found: {path} — run training first")
120
 
121
  def save_head(self, path: Optional[Path] = None):
122
  path = path or (self.models_dir / "poster_sentry_head.npz")
123
  path.parent.mkdir(parents=True, exist_ok=True)
124
- np.savez(path, W=self.W, b=self.b, labels=np.array(self.labels))
 
 
 
 
 
 
 
 
125
 
126
  # ── Feature extraction ──────────────────────────────────────
127
 
128
  def extract_text(self, pdf_path: str, max_chars: int = 4000) -> str:
129
- """Extract and clean text from first page of PDF."""
130
- try:
131
- import fitz
132
- doc = fitz.open(pdf_path)
133
- if len(doc) == 0:
134
- doc.close()
135
- return ""
136
- text = doc[0].get_text()
137
- doc.close()
138
- # Basic cleanup
139
- import re
140
- text = re.sub(r"\s+", " ", text).strip()
141
- return text[:max_chars]
142
- except Exception:
143
- return ""
144
 
145
  def embed_texts(self, texts: List[str]) -> np.ndarray:
146
  """Encode texts with model2vec, L2-normalize."""
@@ -160,6 +184,34 @@ class PosterSentry:
160
 
161
  # ── Inference ───────────────────────────────────────────────
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  def classify(self, pdf_path: str) -> Dict[str, Any]:
164
  """Classify a single PDF as poster or non-poster."""
165
  if not self._initialized:
@@ -193,30 +245,22 @@ class PosterSentry:
193
  visual_arr = np.array(visual_vecs, dtype="float32")
194
  struct_arr = np.array(structural_vecs, dtype="float32")
195
 
196
- # Concatenate
197
- X = np.concatenate([text_embs, visual_arr, struct_arr], axis=1)
198
-
199
- # Scale features (critical for balanced text vs structural signal)
200
- if self.scaler_mean is not None and self.scaler_scale is not None:
201
- X = (X - self.scaler_mean) / np.where(self.scaler_scale == 0, 1, self.scaler_scale)
202
-
203
- # Predict
204
  if self.W is None:
205
  return [{"path": p, "is_poster": False, "confidence": 0.0,
206
  "error": "Model not trained"} for p in pdf_paths]
207
 
208
- logits = X @ self.W + self.b
209
- e = np.exp(logits - logits.max(axis=-1, keepdims=True))
210
- probs = e / e.sum(axis=-1, keepdims=True)
211
 
212
  results = []
213
  for i, p in enumerate(pdf_paths):
214
- poster_prob = float(probs[i, 1])
215
  results.append({
216
  "path": str(p),
217
  "is_poster": poster_prob > 0.5,
218
  "confidence": round(poster_prob, 4),
219
- "text_score": round(float(probs[i, 1]), 4),
 
220
  })
221
  return results
222
 
@@ -237,16 +281,9 @@ class PosterSentry:
237
  # Zero-fill visual and structural features
238
  zeros_visual = np.zeros((len(texts), N_VISUAL_FEATURES), dtype="float32")
239
  zeros_struct = np.zeros((len(texts), N_STRUCTURAL_FEATURES), dtype="float32")
240
- X = np.concatenate([text_embs, zeros_visual, zeros_struct], axis=1)
241
-
242
- # Scale
243
- if self.scaler_mean is not None and self.scaler_scale is not None:
244
- X = (X - self.scaler_mean) / np.where(self.scaler_scale == 0, 1, self.scaler_scale)
245
-
246
- logits = X @ self.W + self.b
247
- e = np.exp(logits - logits.max(axis=-1, keepdims=True))
248
- probs = e / e.sum(axis=-1, keepdims=True)
249
 
250
- return [{"is_poster": float(probs[i, 1]) > 0.5,
251
- "confidence": round(float(probs[i, 1]), 4)}
252
  for i in range(len(texts))]
 
55
  self,
56
  model_name: str = "minishlab/potion-base-32M",
57
  models_dir: Optional[Path] = None,
58
+ backend: str = None,
59
  ):
60
  self.model_name = model_name
61
  self.models_dir = models_dir or self._default_models_dir()
62
  self.models_dir = Path(self.models_dir)
63
 
64
+ # PDF backend: "pdfplumber" (default, matches the released model) or
65
+ # "pymupdf" (faster, AGPL, optional dependency). See features.py.
66
+ from .features import DEFAULT_BACKEND
67
+ self.backend = backend or DEFAULT_BACKEND
68
+
69
  self.text_model = None
70
  self.W: Optional[np.ndarray] = None
71
  self.b: Optional[np.ndarray] = None
 
73
  self.scaler_scale: Optional[np.ndarray] = None
74
  self.labels = ["non_poster", "poster"]
75
 
76
+ # Head architecture. "stacked" heads score the text embedding with a
77
+ # stage-one logistic regression whose poster probability becomes a
78
+ # single text-score feature for the final classifier over
79
+ # [text_score + 15 visual + 15 structural]; "flat" heads classify the
80
+ # raw 542-dimensional concatenation and remain loadable.
81
+ self.arch = "flat"
82
+ self.s1_W: Optional[np.ndarray] = None
83
+ self.s1_b: Optional[np.ndarray] = None
84
+ self.s1_scaler_mean: Optional[np.ndarray] = None
85
+ self.s1_scaler_scale: Optional[np.ndarray] = None
86
+
87
+ self.visual_extractor = VisualFeatureExtractor(backend=self.backend)
88
+ self.structural_extractor = PDFStructuralExtractor(backend=self.backend)
89
  self._initialized = False
90
 
91
  @staticmethod
 
93
  import os
94
  if env := os.environ.get("POSTER_SENTRY_MODELS_DIR"):
95
  return Path(env)
96
+ # Check for bundled models shipped with the package
97
+ pkg_models = Path(__file__).resolve().parent.parent / "models"
98
+ if (pkg_models / "poster_sentry_head.npz").exists():
99
+ return pkg_models
100
+ # Fall back to user-local cache
101
  home = Path.home() / ".poster_sentry" / "models"
102
  home.mkdir(parents=True, exist_ok=True)
103
  return home
 
129
  path = self.models_dir / "poster_sentry_head.npz"
130
  if path.exists():
131
  data = np.load(path, allow_pickle=True)
132
+ self.arch = str(data["arch"]) if "arch" in data.files else "flat"
133
  self.W = data["W"]
134
  self.b = data["b"]
135
  if "labels" in data:
 
137
  if "scaler_mean" in data and "scaler_scale" in data:
138
  self.scaler_mean = data["scaler_mean"]
139
  self.scaler_scale = data["scaler_scale"]
140
+ if self.arch == "stacked":
141
+ self.s1_W = data["s1_W"]
142
+ self.s1_b = data["s1_b"]
143
+ self.s1_scaler_mean = data["s1_scaler_mean"]
144
+ self.s1_scaler_scale = data["s1_scaler_scale"]
145
+ logger.info(f" Loaded classifier head ({self.arch}): {path}")
146
  else:
147
  logger.warning(f" Head not found: {path} — run training first")
148
 
149
  def save_head(self, path: Optional[Path] = None):
150
  path = path or (self.models_dir / "poster_sentry_head.npz")
151
  path.parent.mkdir(parents=True, exist_ok=True)
152
+ payload = dict(W=self.W, b=self.b, labels=np.array(self.labels),
153
+ arch=np.array(self.arch))
154
+ if self.scaler_mean is not None:
155
+ payload.update(scaler_mean=self.scaler_mean, scaler_scale=self.scaler_scale)
156
+ if self.arch == "stacked":
157
+ payload.update(s1_W=self.s1_W, s1_b=self.s1_b,
158
+ s1_scaler_mean=self.s1_scaler_mean,
159
+ s1_scaler_scale=self.s1_scaler_scale)
160
+ np.savez(path, **payload)
161
 
162
  # ── Feature extraction ──────────────────────────────────────
163
 
164
  def extract_text(self, pdf_path: str, max_chars: int = 4000) -> str:
165
+ """Extract and clean first-page text with the selected backend."""
166
+ from .features import extract_first_page_text
167
+ return extract_first_page_text(pdf_path, backend=self.backend, max_chars=max_chars)
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  def embed_texts(self, texts: List[str]) -> np.ndarray:
170
  """Encode texts with model2vec, L2-normalize."""
 
184
 
185
  # ── Inference ───────────────────────────────────────────────
186
 
187
+ @staticmethod
188
+ def _softmax(logits: np.ndarray) -> np.ndarray:
189
+ e = np.exp(logits - logits.max(axis=-1, keepdims=True))
190
+ return e / e.sum(axis=-1, keepdims=True)
191
+
192
+ def _poster_col(self) -> int:
193
+ try:
194
+ return self.labels.index("poster")
195
+ except ValueError:
196
+ return 1
197
+
198
+ def _score_features(self, text_embs, visual_arr, struct_arr):
199
+ """Class probabilities (n, 2) and, for stacked heads, the text score."""
200
+ ip = self._poster_col()
201
+ text_scores = None
202
+ if self.arch == "stacked":
203
+ T = (text_embs - self.s1_scaler_mean) / np.where(
204
+ self.s1_scaler_scale == 0, 1, self.s1_scaler_scale)
205
+ text_scores = self._softmax(T @ self.s1_W + self.s1_b)[:, ip]
206
+ X = np.concatenate(
207
+ [text_scores[:, None].astype("float32"), visual_arr, struct_arr], axis=1)
208
+ else:
209
+ X = np.concatenate([text_embs, visual_arr, struct_arr], axis=1)
210
+ if self.scaler_mean is not None and self.scaler_scale is not None:
211
+ X = (X - self.scaler_mean) / np.where(self.scaler_scale == 0, 1, self.scaler_scale)
212
+ probs = self._softmax(X @ self.W + self.b)
213
+ return probs, text_scores
214
+
215
  def classify(self, pdf_path: str) -> Dict[str, Any]:
216
  """Classify a single PDF as poster or non-poster."""
217
  if not self._initialized:
 
245
  visual_arr = np.array(visual_vecs, dtype="float32")
246
  struct_arr = np.array(structural_vecs, dtype="float32")
247
 
 
 
 
 
 
 
 
 
248
  if self.W is None:
249
  return [{"path": p, "is_poster": False, "confidence": 0.0,
250
  "error": "Model not trained"} for p in pdf_paths]
251
 
252
+ probs, text_scores = self._score_features(text_embs, visual_arr, struct_arr)
253
+ ip = self._poster_col()
 
254
 
255
  results = []
256
  for i, p in enumerate(pdf_paths):
257
+ poster_prob = float(probs[i, ip])
258
  results.append({
259
  "path": str(p),
260
  "is_poster": poster_prob > 0.5,
261
  "confidence": round(poster_prob, 4),
262
+ "text_score": round(float(text_scores[i]) if text_scores is not None
263
+ else poster_prob, 4),
264
  })
265
  return results
266
 
 
281
  # Zero-fill visual and structural features
282
  zeros_visual = np.zeros((len(texts), N_VISUAL_FEATURES), dtype="float32")
283
  zeros_struct = np.zeros((len(texts), N_STRUCTURAL_FEATURES), dtype="float32")
284
+ probs, _ = self._score_features(text_embs, zeros_visual, zeros_struct)
285
+ ip = self._poster_col()
 
 
 
 
 
 
 
286
 
287
+ return [{"is_poster": float(probs[i, ip]) > 0.5,
288
+ "confidence": round(float(probs[i, ip]), 4)}
289
  for i in range(len(texts))]
src/poster_sentry/cli.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PosterSentry CLI — classify PDFs as scientific posters or non-posters.
3
+
4
+ Usage:
5
+ poster-sentry classify document.pdf
6
+ poster-sentry classify *.pdf --output results.tsv
7
+ poster-sentry info
8
+ """
9
+
10
+ import argparse
11
+ import csv
12
+ import json
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+ from typing import List
17
+
18
+
19
+ def classify_cmd(args):
20
+ """Classify one or more PDFs."""
21
+ from .classifier import PosterSentry
22
+
23
+ sentry = PosterSentry(
24
+ models_dir=Path(args.models_dir) if args.models_dir else None,
25
+ backend=args.backend,
26
+ )
27
+ sentry.initialize()
28
+
29
+ results = []
30
+ for pdf_path in args.pdfs:
31
+ p = Path(pdf_path)
32
+ if not p.exists():
33
+ print(f" SKIP {p.name} (file not found)", file=sys.stderr)
34
+ continue
35
+ t0 = time.time()
36
+ result = sentry.classify(str(p))
37
+ elapsed = time.time() - t0
38
+ result["elapsed_s"] = round(elapsed, 3)
39
+ results.append(result)
40
+
41
+ icon = "POSTER" if result["is_poster"] else "NON-POSTER"
42
+ print(
43
+ f" {icon:11s} conf={result['confidence']:.3f} "
44
+ f"({elapsed:.2f}s) {p.name}"
45
+ )
46
+
47
+ if args.output:
48
+ out = Path(args.output)
49
+ with open(out, "w", newline="") as f:
50
+ writer = csv.writer(f, delimiter="\t")
51
+ writer.writerow(["path", "is_poster", "confidence"])
52
+ for r in results:
53
+ writer.writerow([r["path"], r["is_poster"], r["confidence"]])
54
+ print(f"\nResults written to {out}")
55
+
56
+ if args.json:
57
+ print(json.dumps(results, indent=2))
58
+
59
+
60
+ def info_cmd(args):
61
+ """Print model info."""
62
+ from . import __version__
63
+
64
+ print(f"PosterSentry v{__version__}")
65
+ print(f" Architecture: model2vec (512-d) + visual (15-d) + structural (15-d)")
66
+ print(f" Total features: 542")
67
+ print(f" Classifier: LogisticRegression + StandardScaler")
68
+ print(f" Embedding: minishlab/potion-base-32M")
69
+ from .features import DEFAULT_BACKEND
70
+ print(f" PDF backend: {DEFAULT_BACKEND} (default); pymupdf available with [pymupdf] extra")
71
+ print(f" License: MIT")
72
+ print(f" HuggingFace: huggingface.co/fairdataihub/poster-sentry")
73
+
74
+
75
+ def main():
76
+ parser = argparse.ArgumentParser(
77
+ prog="poster-sentry",
78
+ description="Classify PDFs as scientific posters or non-posters.",
79
+ )
80
+ subparsers = parser.add_subparsers(dest="command")
81
+
82
+ # classify
83
+ p_cls = subparsers.add_parser("classify", help="Classify PDF(s)")
84
+ p_cls.add_argument("pdfs", nargs="+", help="PDF file(s) to classify")
85
+ p_cls.add_argument("--output", "-o", help="Write TSV results to file")
86
+ p_cls.add_argument("--json", action="store_true", help="Print JSON output")
87
+ p_cls.add_argument("--models-dir", default=None, help="Path to models directory")
88
+ p_cls.add_argument(
89
+ "--backend", default=None, choices=["pdfplumber", "pymupdf"],
90
+ help="PDF backend: pdfplumber (default, matches the released model) or "
91
+ "pymupdf (faster, AGPL, needs 'pip install poster-sentry[pymupdf]')",
92
+ )
93
+ p_cls.set_defaults(func=classify_cmd)
94
+
95
+ # info
96
+ p_info = subparsers.add_parser("info", help="Print model info")
97
+ p_info.set_defaults(func=info_cmd)
98
+
99
+ args = parser.parse_args()
100
+ if not args.command:
101
+ parser.print_help()
102
+ sys.exit(1)
103
+
104
+ args.func(args)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
src/poster_sentry/features.py CHANGED
@@ -5,11 +5,27 @@ Two feature channels:
5
  1. Visual features — image-level statistics (color, edges, FFT, whitespace)
6
  2. PDF structural features — page geometry, text blocks, font diversity
7
 
8
- Both are cheap to compute (no GPU needed), providing strong priors that
9
- complement the text embedding from model2vec.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  """
11
 
12
  import logging
 
13
  from pathlib import Path
14
  from typing import Dict, List, Optional, Tuple
15
 
@@ -17,6 +33,43 @@ import numpy as np
17
 
18
  logger = logging.getLogger(__name__)
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # ── Visual Feature Extractor ────────────────────────────────────
21
 
22
  VISUAL_FEATURE_NAMES = [
@@ -41,31 +94,71 @@ class VisualFeatureExtractor:
41
 
42
  FEATURE_NAMES = VISUAL_FEATURE_NAMES
43
 
44
- def __init__(self, target_size: Tuple[int, int] = (256, 256)):
 
 
 
 
 
 
 
 
 
45
  self.target_size = target_size
 
 
46
 
47
  def pdf_to_image(self, pdf_path: str, dpi: int = 72) -> Optional[np.ndarray]:
48
- """Render first page of PDF to RGB numpy array."""
49
  try:
50
- import fitz
51
- doc = fitz.open(pdf_path)
52
- if len(doc) == 0:
53
- doc.close()
54
- return None
55
- page = doc[0]
56
- mat = fitz.Matrix(dpi / 72, dpi / 72)
57
- pix = page.get_pixmap(matrix=mat)
58
- img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, pix.n)
59
- if pix.n == 4:
60
- img = img[:, :, :3]
61
- elif pix.n == 1:
62
- img = np.stack([img[:, :, 0]] * 3, axis=-1)
63
- doc.close()
64
- return img
65
  except Exception as e:
66
- logger.debug(f"PDF to image failed: {e}")
 
67
  return None
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def extract(self, image: np.ndarray) -> Dict[str, float]:
70
  """Extract 15 visual features from an RGB image."""
71
  feats = {n: 0.0 for n in self.FEATURE_NAMES}
@@ -73,6 +166,9 @@ class VisualFeatureExtractor:
73
  from PIL import Image as PILImage
74
 
75
  h, w = image.shape[:2]
 
 
 
76
  feats["img_width"] = float(w)
77
  feats["img_height"] = float(h)
78
  feats["img_aspect_ratio"] = w / h if h > 0 else 0.0
@@ -87,18 +183,15 @@ class VisualFeatureExtractor:
87
  gray = np.mean(resized, axis=2)
88
  feats["local_contrast"] = float(np.std(gray))
89
 
90
- # Color diversity (unique quantized colors in 32x32 thumbnail)
91
  small = np.array(pil.resize((32, 32)))
92
  quantized = (small // 32).astype(np.uint8)
93
  unique_colors = len(np.unique(quantized.reshape(-1, 3), axis=0))
94
  feats["color_diversity"] = unique_colors / 512.0
95
 
96
- # Edge density
97
  gy = np.abs(np.diff(gray, axis=0))
98
  gx = np.abs(np.diff(gray, axis=1))
99
  feats["edge_density"] = float(np.mean(gy) + np.mean(gx)) / 255.0
100
 
101
- # Spatial complexity (high-freq ratio via FFT)
102
  fft = np.fft.fft2(gray)
103
  fft_shift = np.fft.fftshift(fft)
104
  mag = np.abs(fft_shift)
@@ -110,11 +203,9 @@ class VisualFeatureExtractor:
110
  low_e = np.sum(mag[center_mask] ** 2)
111
  feats["spatial_complexity"] = 1.0 - (low_e / total_e) if total_e > 0 else 0.0
112
 
113
- # White space ratio
114
  white_px = np.sum(np.all(resized > 240, axis=2))
115
  feats["white_space_ratio"] = white_px / (self.target_size[0] * self.target_size[1])
116
 
117
- # High contrast ratio (very dark + very bright pixels)
118
  feats["high_contrast_ratio"] = float(np.sum(gray < 50) + np.sum(gray > 240)) / gray.size
119
 
120
  except Exception as e:
@@ -148,69 +239,126 @@ STRUCTURAL_FEATURE_NAMES = [
148
  N_STRUCTURAL_FEATURES = len(STRUCTURAL_FEATURE_NAMES)
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  class PDFStructuralExtractor:
152
  """Extract structural features from PDF layout."""
153
 
154
  FEATURE_NAMES = STRUCTURAL_FEATURE_NAMES
155
 
 
 
 
156
  def extract(self, pdf_path: str) -> Dict[str, float]:
157
- """Extract 15 structural features from a PDF."""
158
  feats = {n: 0.0 for n in self.FEATURE_NAMES}
159
  try:
160
- import fitz
161
- path = Path(pdf_path)
162
- doc = fitz.open(str(path))
163
- if len(doc) == 0:
164
- doc.close()
165
- return feats
166
 
167
- feats["page_count"] = float(len(doc))
 
 
 
 
 
 
 
168
  feats["file_size_kb"] = path.stat().st_size / 1024.0
169
- feats["size_per_page_kb"] = feats["file_size_kb"] / max(len(doc), 1)
170
-
171
- page = doc[0]
172
- rect = page.rect
173
- feats["page_width_pt"] = rect.width
174
- feats["page_height_pt"] = rect.height
175
- feats["page_aspect_ratio"] = rect.width / rect.height if rect.height > 0 else 0.0
176
- feats["page_area_sqin"] = (rect.width / 72.0) * (rect.height / 72.0)
177
- feats["is_landscape"] = float(rect.width > rect.height)
178
-
179
- # Text blocks
180
- blocks = page.get_text("dict")["blocks"]
181
- text_blocks = [b for b in blocks if b.get("type") == 0]
182
- feats["text_block_count"] = float(len(text_blocks))
183
-
184
- if text_blocks:
185
- heights = [b["bbox"][3] - b["bbox"][1] for b in text_blocks]
186
- widths = [b["bbox"][2] - b["bbox"][0] for b in text_blocks]
187
- total_area = sum(h * w for h, w in zip(heights, widths))
188
- page_area = rect.width * rect.height
189
- feats["text_density"] = total_area / page_area if page_area > 0 else 0.0
190
-
191
- # Font statistics
192
- fonts = set()
193
- font_sizes = []
194
- line_count = 0
195
- for block in text_blocks:
196
- for line in block.get("lines", []):
197
- line_count += 1
198
- for span in line.get("spans", []):
199
- fonts.add(span.get("font", ""))
200
- sz = span.get("size", 0)
201
- if sz > 0:
202
- font_sizes.append(sz)
203
-
204
  feats["font_count"] = float(len(fonts))
205
- feats["line_count"] = float(line_count)
206
  if font_sizes:
207
  feats["avg_font_size"] = float(np.mean(font_sizes))
208
  feats["font_size_variance"] = float(np.var(font_sizes)) if len(font_sizes) > 1 else 0.0
209
- feats["title_score"] = max(font_sizes) / (np.mean(font_sizes) + 1.0)
 
210
 
 
 
 
 
 
211
  doc.close()
212
- except Exception as e:
213
- logger.debug(f"PDF structural extraction failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  return feats
215
 
216
  def to_vector(self, feats: Dict[str, float]) -> np.ndarray:
 
5
  1. Visual features — image-level statistics (color, edges, FFT, whitespace)
6
  2. PDF structural features — page geometry, text blocks, font diversity
7
 
8
+ PDF access supports selectable backends:
9
+
10
+ "pdfplumber" (default)
11
+ pdfplumber for text and structure (MIT) and pypdfium2 for page
12
+ rendering (BSD). First-page text is read with the poster2json layout
13
+ engine (MIT, vendored in ``poster_sentry.p2j``) on top of pdfplumber.
14
+ This permissively licensed stack was used to train and evaluate the
15
+ released model, so it is the default and the one the paper reports.
16
+
17
+ "pymupdf"
18
+ PyMuPDF (fitz) for text, structure, and rendering. Faster, but PyMuPDF
19
+ is AGPL-licensed, and its extracted features differ slightly from the
20
+ default, so the released model is matched to the "pdfplumber" backend.
21
+ Install the optional dependency with `pip install poster-sentry[pymupdf]`.
22
+
23
+ Select the backend with the ``backend`` argument or the
24
+ ``POSTER_SENTRY_BACKEND`` environment variable. The default is "pdfplumber".
25
  """
26
 
27
  import logging
28
+ import os
29
  from pathlib import Path
30
  from typing import Dict, List, Optional, Tuple
31
 
 
33
 
34
  logger = logging.getLogger(__name__)
35
 
36
+ DEFAULT_BACKEND = os.environ.get("POSTER_SENTRY_BACKEND", "pdfplumber")
37
+ BACKENDS = ("pdfplumber", "pymupdf")
38
+
39
+
40
+ def extract_first_page_text(pdf_path: str, backend: str = None, max_chars: int = 4000) -> str:
41
+ """Extract and clean first-page text with the selected backend.
42
+
43
+ The pdfplumber backend reads the first page with the poster2json layout
44
+ engine (vendored in ``poster_sentry.p2j``), which rebuilds reading order
45
+ from the PDF content stream; when that returns no text, pdfplumber's own
46
+ ``extract_text`` is used. This is the extraction the released model was
47
+ trained on.
48
+ """
49
+ import re
50
+ backend = backend or DEFAULT_BACKEND
51
+ try:
52
+ if backend == "pymupdf":
53
+ import fitz
54
+ doc = fitz.open(pdf_path)
55
+ text = doc[0].get_text() if len(doc) else ""
56
+ doc.close()
57
+ else:
58
+ from .p2j import extract_text_with_pdfplumber
59
+ try:
60
+ text = extract_text_with_pdfplumber(pdf_path, max_pages=1) or ""
61
+ except Exception as e:
62
+ logger.debug(f"poster2json text path failed: {e}")
63
+ text = ""
64
+ if not text.strip():
65
+ import pdfplumber
66
+ with pdfplumber.open(pdf_path) as doc:
67
+ text = (doc.pages[0].extract_text() or "") if doc.pages else ""
68
+ return re.sub(r"\s+", " ", text).strip()[:max_chars]
69
+ except Exception:
70
+ return ""
71
+
72
+
73
  # ── Visual Feature Extractor ────────────────────────────────────
74
 
75
  VISUAL_FEATURE_NAMES = [
 
94
 
95
  FEATURE_NAMES = VISUAL_FEATURE_NAMES
96
 
97
+ # Cap on first-page rasterization, in pixels. Pages whose render at the
98
+ # requested dpi would exceed this budget are rasterized at a reduced
99
+ # scale, while the reported image dimensions (the img_width and
100
+ # img_height features) keep their nominal values, so feature semantics
101
+ # are unchanged for every document. This bounds render memory on very
102
+ # large pages; it does not bound render time on content-pathological
103
+ # PDFs, which only process isolation can.
104
+ MAX_RENDER_PIXELS = 32_000_000
105
+
106
+ def __init__(self, target_size: Tuple[int, int] = (256, 256), backend: str = None):
107
  self.target_size = target_size
108
+ self.backend = backend or DEFAULT_BACKEND
109
+ self._nominal_size: Optional[Tuple[int, int]] = None
110
 
111
  def pdf_to_image(self, pdf_path: str, dpi: int = 72) -> Optional[np.ndarray]:
112
+ """Render first page of PDF to RGB numpy array with the selected backend."""
113
  try:
114
+ if self.backend == "pymupdf":
115
+ return self._render_pymupdf(pdf_path, dpi)
116
+ return self._render_pypdfium2(pdf_path, dpi)
 
 
 
 
 
 
 
 
 
 
 
 
117
  except Exception as e:
118
+ self._nominal_size = None
119
+ logger.debug(f"PDF to image failed ({self.backend}): {e}")
120
  return None
121
 
122
+ def _render_pypdfium2(self, pdf_path: str, dpi: int) -> Optional[np.ndarray]:
123
+ import pypdfium2 as pdfium
124
+ pdf = pdfium.PdfDocument(pdf_path)
125
+ if len(pdf) == 0:
126
+ pdf.close()
127
+ return None
128
+ page = pdf[0]
129
+ w_pt, h_pt = page.get_size()
130
+ scale = dpi / 72.0
131
+ nominal_px = (w_pt * scale) * (h_pt * scale)
132
+ if nominal_px > self.MAX_RENDER_PIXELS:
133
+ self._nominal_size = (int(round(w_pt * scale)), int(round(h_pt * scale)))
134
+ scale *= (self.MAX_RENDER_PIXELS / nominal_px) ** 0.5
135
+ img = np.array(page.render(scale=scale).to_pil().convert("RGB"))
136
+ page.close()
137
+ pdf.close()
138
+ return img
139
+
140
+ def _render_pymupdf(self, pdf_path: str, dpi: int) -> Optional[np.ndarray]:
141
+ import fitz
142
+ doc = fitz.open(pdf_path)
143
+ if len(doc) == 0:
144
+ doc.close()
145
+ return None
146
+ page = doc[0]
147
+ zoom = dpi / 72.0
148
+ rect = page.rect
149
+ nominal_px = (rect.width * zoom) * (rect.height * zoom)
150
+ if nominal_px > self.MAX_RENDER_PIXELS:
151
+ self._nominal_size = (int(round(rect.width * zoom)), int(round(rect.height * zoom)))
152
+ zoom *= (self.MAX_RENDER_PIXELS / nominal_px) ** 0.5
153
+ pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))
154
+ img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, pix.n)
155
+ if pix.n == 4:
156
+ img = img[:, :, :3]
157
+ elif pix.n == 1:
158
+ img = np.stack([img[:, :, 0]] * 3, axis=-1)
159
+ doc.close()
160
+ return img
161
+
162
  def extract(self, image: np.ndarray) -> Dict[str, float]:
163
  """Extract 15 visual features from an RGB image."""
164
  feats = {n: 0.0 for n in self.FEATURE_NAMES}
 
166
  from PIL import Image as PILImage
167
 
168
  h, w = image.shape[:2]
169
+ if self._nominal_size is not None:
170
+ w, h = self._nominal_size
171
+ self._nominal_size = None
172
  feats["img_width"] = float(w)
173
  feats["img_height"] = float(h)
174
  feats["img_aspect_ratio"] = w / h if h > 0 else 0.0
 
183
  gray = np.mean(resized, axis=2)
184
  feats["local_contrast"] = float(np.std(gray))
185
 
 
186
  small = np.array(pil.resize((32, 32)))
187
  quantized = (small // 32).astype(np.uint8)
188
  unique_colors = len(np.unique(quantized.reshape(-1, 3), axis=0))
189
  feats["color_diversity"] = unique_colors / 512.0
190
 
 
191
  gy = np.abs(np.diff(gray, axis=0))
192
  gx = np.abs(np.diff(gray, axis=1))
193
  feats["edge_density"] = float(np.mean(gy) + np.mean(gx)) / 255.0
194
 
 
195
  fft = np.fft.fft2(gray)
196
  fft_shift = np.fft.fftshift(fft)
197
  mag = np.abs(fft_shift)
 
203
  low_e = np.sum(mag[center_mask] ** 2)
204
  feats["spatial_complexity"] = 1.0 - (low_e / total_e) if total_e > 0 else 0.0
205
 
 
206
  white_px = np.sum(np.all(resized > 240, axis=2))
207
  feats["white_space_ratio"] = white_px / (self.target_size[0] * self.target_size[1])
208
 
 
209
  feats["high_contrast_ratio"] = float(np.sum(gray < 50) + np.sum(gray > 240)) / gray.size
210
 
211
  except Exception as e:
 
239
  N_STRUCTURAL_FEATURES = len(STRUCTURAL_FEATURE_NAMES)
240
 
241
 
242
+ def _count_text_blocks(lines: List[dict]) -> int:
243
+ """Group text lines into blocks by vertical spacing (pdfplumber backend)."""
244
+ if not lines:
245
+ return 0
246
+ lines = sorted(lines, key=lambda ln: ln["top"])
247
+ heights = [max(ln["bottom"] - ln["top"], 1.0) for ln in lines]
248
+ median_h = float(np.median(heights))
249
+ blocks = 1
250
+ for prev, cur in zip(lines, lines[1:]):
251
+ if cur["top"] - prev["bottom"] > median_h:
252
+ blocks += 1
253
+ return blocks
254
+
255
+
256
  class PDFStructuralExtractor:
257
  """Extract structural features from PDF layout."""
258
 
259
  FEATURE_NAMES = STRUCTURAL_FEATURE_NAMES
260
 
261
+ def __init__(self, backend: str = None):
262
+ self.backend = backend or DEFAULT_BACKEND
263
+
264
  def extract(self, pdf_path: str) -> Dict[str, float]:
265
+ """Extract 15 structural features from a PDF with the selected backend."""
266
  feats = {n: 0.0 for n in self.FEATURE_NAMES}
267
  try:
268
+ if self.backend == "pymupdf":
269
+ return self._extract_pymupdf(pdf_path, feats)
270
+ return self._extract_pdfplumber(pdf_path, feats)
271
+ except Exception as e:
272
+ logger.debug(f"PDF structural extraction failed ({self.backend}): {e}")
273
+ return feats
274
 
275
+ def _extract_pdfplumber(self, pdf_path: str, feats: Dict[str, float]) -> Dict[str, float]:
276
+ import pdfplumber
277
+ path = Path(pdf_path)
278
+ with pdfplumber.open(str(path)) as doc:
279
+ n_pages = len(doc.pages)
280
+ if n_pages == 0:
281
+ return feats
282
+ feats["page_count"] = float(n_pages)
283
  feats["file_size_kb"] = path.stat().st_size / 1024.0
284
+ feats["size_per_page_kb"] = feats["file_size_kb"] / max(n_pages, 1)
285
+
286
+ page = doc.pages[0]
287
+ pw, ph = float(page.width), float(page.height)
288
+ feats["page_width_pt"] = pw
289
+ feats["page_height_pt"] = ph
290
+ feats["page_aspect_ratio"] = pw / ph if ph > 0 else 0.0
291
+ feats["page_area_sqin"] = (pw / 72.0) * (ph / 72.0)
292
+ feats["is_landscape"] = float(pw > ph)
293
+
294
+ chars = page.chars
295
+ words = page.extract_words()
296
+ lines = page.extract_text_lines()
297
+ feats["text_block_count"] = float(_count_text_blocks(lines))
298
+ feats["line_count"] = float(len(lines))
299
+ if words:
300
+ word_area = sum(
301
+ max(wd["x1"] - wd["x0"], 0.0) * max(wd["bottom"] - wd["top"], 0.0)
302
+ for wd in words
303
+ )
304
+ page_area = pw * ph
305
+ feats["text_density"] = word_area / page_area if page_area > 0 else 0.0
306
+ fonts = {c.get("fontname", "") for c in chars if c.get("fontname")}
307
+ font_sizes = [float(c["size"]) for c in chars if c.get("size", 0)]
 
 
 
 
 
 
 
 
 
 
 
308
  feats["font_count"] = float(len(fonts))
 
309
  if font_sizes:
310
  feats["avg_font_size"] = float(np.mean(font_sizes))
311
  feats["font_size_variance"] = float(np.var(font_sizes)) if len(font_sizes) > 1 else 0.0
312
+ feats["title_score"] = max(font_sizes) / (float(np.mean(font_sizes)) + 1.0)
313
+ return feats
314
 
315
+ def _extract_pymupdf(self, pdf_path: str, feats: Dict[str, float]) -> Dict[str, float]:
316
+ import fitz
317
+ path = Path(pdf_path)
318
+ doc = fitz.open(str(path))
319
+ if len(doc) == 0:
320
  doc.close()
321
+ return feats
322
+ feats["page_count"] = float(len(doc))
323
+ feats["file_size_kb"] = path.stat().st_size / 1024.0
324
+ feats["size_per_page_kb"] = feats["file_size_kb"] / max(len(doc), 1)
325
+
326
+ page = doc[0]
327
+ rect = page.rect
328
+ feats["page_width_pt"] = rect.width
329
+ feats["page_height_pt"] = rect.height
330
+ feats["page_aspect_ratio"] = rect.width / rect.height if rect.height > 0 else 0.0
331
+ feats["page_area_sqin"] = (rect.width / 72.0) * (rect.height / 72.0)
332
+ feats["is_landscape"] = float(rect.width > rect.height)
333
+
334
+ blocks = page.get_text("dict")["blocks"]
335
+ text_blocks = [b for b in blocks if b.get("type") == 0]
336
+ feats["text_block_count"] = float(len(text_blocks))
337
+ if text_blocks:
338
+ heights = [b["bbox"][3] - b["bbox"][1] for b in text_blocks]
339
+ widths = [b["bbox"][2] - b["bbox"][0] for b in text_blocks]
340
+ total_area = sum(h * w for h, w in zip(heights, widths))
341
+ page_area = rect.width * rect.height
342
+ feats["text_density"] = total_area / page_area if page_area > 0 else 0.0
343
+
344
+ fonts = set()
345
+ font_sizes = []
346
+ line_count = 0
347
+ for block in text_blocks:
348
+ for line in block.get("lines", []):
349
+ line_count += 1
350
+ for span in line.get("spans", []):
351
+ fonts.add(span.get("font", ""))
352
+ sz = span.get("size", 0)
353
+ if sz > 0:
354
+ font_sizes.append(sz)
355
+ feats["font_count"] = float(len(fonts))
356
+ feats["line_count"] = float(line_count)
357
+ if font_sizes:
358
+ feats["avg_font_size"] = float(np.mean(font_sizes))
359
+ feats["font_size_variance"] = float(np.var(font_sizes)) if len(font_sizes) > 1 else 0.0
360
+ feats["title_score"] = max(font_sizes) / (np.mean(font_sizes) + 1.0)
361
+ doc.close()
362
  return feats
363
 
364
  def to_vector(self, feats: Dict[str, float]) -> np.ndarray:
src/poster_sentry/p2j/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Vendored poster2json pdfplumber text path (MIT); see text.py."""
2
+ from .text import extract_text_with_pdfplumber
3
+
4
+ __all__ = ["extract_text_with_pdfplumber"]
src/poster_sentry/p2j/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (353 Bytes). View file
 
src/poster_sentry/p2j/__pycache__/text.cpython-312.pyc ADDED
Binary file (53.8 kB). View file
 
src/poster_sentry/p2j/layout_blocks.py ADDED
@@ -0,0 +1,788 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Leaf-aware line, word and block helpers for the pdfplumber text path.
2
+
3
+ Pure functions over pdfplumber char/word dicts (x0, x1, top, bottom, size,
4
+ fontname, text), so they can be unit tested with synthetic dicts.
5
+
6
+ The XY-cut tree in ``xy_cut`` decides reading order and yields leaves. The
7
+ helpers here build lines and words *inside* each leaf, from the same chars,
8
+ so every word belongs to exactly one line and nothing is matched back by
9
+ bounding box.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import bisect
15
+ import re
16
+ import statistics
17
+ from collections import Counter
18
+ from typing import Dict, List, Optional, Sequence, Tuple
19
+
20
+ # Feature switches. All on by default; the offline A/B harness flips them
21
+ # one at a time to measure each step.
22
+ FLAGS: Dict[str, bool] = {
23
+ "leaf": True, # force block breaks at XY-cut leaf boundaries / upward jumps
24
+ "decomp": True, # words and lines built from the same chars, per leaf
25
+ "body_tol": True, # baseline tolerance from page body font size
26
+ "sup": True, # attach small raised/lowered chars to their line
27
+ "fig": True, # separate figure/table label text from body paragraphs
28
+ "hyphen": True, # join words hyphenated at line ends
29
+ "dedupe": True, # drop overprinted duplicate glyphs
30
+ "rotated": True, # keep rotated text (axis labels, sidebars) as whole words
31
+ }
32
+
33
+ BASELINE_RANGE = 0.5 # same value as xy_cut.BASELINE_RANGE
34
+ SMALL_RATIO = 0.8 # chars below this fraction of the leaf size may be sup/sub
35
+ ATTACH_GAP_EM = 0.5 # max horizontal gap (in line sizes) to a main char
36
+ ATTACH_OVERLAP = 0.5 # fraction of the small char that must sit in the line band
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # font size helpers
41
+ # ---------------------------------------------------------------------------
42
+
43
+ def _size(c: dict) -> float:
44
+ s = c.get("size")
45
+ if s is None or s <= 0:
46
+ s = c["bottom"] - c["top"]
47
+ return s
48
+
49
+
50
+ def mode_size(chars: Sequence[dict]) -> float:
51
+ """Most common char size (rounded to 0.5 pt), ties go to the larger size."""
52
+ sizes = [round(_size(c) * 2) / 2 for c in chars if c.get("text", "").strip()]
53
+ if not sizes:
54
+ return 0.0
55
+ cnt = Counter(sizes)
56
+ best = max(cnt.items(), key=lambda kv: (kv[1], kv[0]))
57
+ return float(best[0])
58
+
59
+
60
+ body_font_size = mode_size
61
+
62
+
63
+ def line_order(chars: Sequence[dict]) -> List[dict]:
64
+ """Order the chars of one line.
65
+
66
+ PDF stream order when every char carries its stream index (key "_si"),
67
+ which keeps a string drawn twice (shadow, fake bold) as two separate runs
68
+ instead of interleaving the two copies; left to right otherwise.
69
+ """
70
+ if chars and all("_si" in c for c in chars):
71
+ return sorted(chars, key=lambda c: c["_si"])
72
+ return sorted(chars, key=lambda c: c["x0"])
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # lines
77
+ # ---------------------------------------------------------------------------
78
+
79
+ def _cluster_by_baseline(chars: Sequence[dict], tol: float) -> List[List[dict]]:
80
+ """Group chars into lines by (running mean) bottom coordinate."""
81
+ if not chars:
82
+ return []
83
+ chars = sorted(chars, key=lambda c: (c["bottom"], c["x0"]))
84
+ lines: List[List[dict]] = []
85
+ cur = [chars[0]]
86
+ base_sum = chars[0]["bottom"]
87
+ for c in chars[1:]:
88
+ base = base_sum / len(cur)
89
+ if abs(c["bottom"] - base) <= tol:
90
+ cur.append(c)
91
+ base_sum += c["bottom"]
92
+ else:
93
+ lines.append(cur)
94
+ cur = [c]
95
+ base_sum = c["bottom"]
96
+ lines.append(cur)
97
+ return lines
98
+
99
+
100
+ def _line_band(line: Sequence[dict]) -> Tuple[float, float, float]:
101
+ top = min(c["top"] for c in line)
102
+ bottom = max(c["bottom"] for c in line)
103
+ return top, bottom, mode_size(line) or (bottom - top)
104
+
105
+
106
+ def _hgap(a: dict, b: dict) -> float:
107
+ return max(a["x0"] - b["x1"], b["x0"] - a["x1"], 0.0)
108
+
109
+
110
+ def _attach_small(lines: List[List[dict]], small: Sequence[dict]) -> List[dict]:
111
+ """Attach small raised/lowered chars to the line they belong to.
112
+
113
+ A small char joins a line when it sits mostly inside the line's vertical
114
+ band (extended a little) and touches a main char horizontally. Among the
115
+ candidate lines the choice is, in order: the line whose own band (no
116
+ extension) contains the char's vertical centre, then the smallest
117
+ horizontal gap to one of its chars, then the largest vertical overlap.
118
+ It is never the nearest line centre, so a marker raised from a name does
119
+ not jump to a bigger-font line that happens to sit just above or below.
120
+ Host lines much bigger than the marker (more than 2.2x) are skipped.
121
+ Returns the chars that could not be attached.
122
+ """
123
+ bands = [_line_band(ln) for ln in lines]
124
+ leftover = []
125
+ for c in small:
126
+ ch = max(c["bottom"] - c["top"], 0.1)
127
+ cy = (c["top"] + c["bottom"]) / 2
128
+ best = None
129
+ best_key = None
130
+ for idx, (ln, (top, bottom, lsize)) in enumerate(zip(lines, bands)):
131
+ if lsize > 2.2 * _size(c):
132
+ continue
133
+ lo, hi = top - 0.3 * lsize, bottom + 0.3 * lsize
134
+ ov = min(c["bottom"], hi) - max(c["top"], lo)
135
+ if ov < ATTACH_OVERLAP * ch:
136
+ continue
137
+ gap = min(_hgap(c, m) for m in ln)
138
+ if gap > ATTACH_GAP_EM * lsize:
139
+ continue
140
+ inside = top <= cy <= bottom
141
+ key = (0 if inside else 1, gap, -ov)
142
+ if best_key is None or key < best_key:
143
+ best, best_key = idx, key
144
+ if best is None:
145
+ leftover.append(c)
146
+ else:
147
+ lines[best].append(c)
148
+ return leftover
149
+
150
+
151
+ def _local_small(chars: Sequence[dict]) -> set:
152
+ """Ids of chars that are clearly smaller than an adjacent same-row char.
153
+
154
+ A char is a marker candidate when a horizontally adjacent char (gap under
155
+ half its own size) is at least 1.25x bigger and the small char's vertical
156
+ centre lies within that neighbour's box. This finds author affiliation
157
+ markers on a line whose leaf mixes other sizes, where the leaf's dominant
158
+ size is not the host line's size.
159
+ """
160
+ cell = 64.0
161
+ grid: Dict[Tuple[int, int], List[dict]] = {}
162
+ for c in chars:
163
+ grid.setdefault((int(c["x0"] // cell), int(c["top"] // cell)), []).append(c)
164
+ out = set()
165
+ for c in chars:
166
+ sz = _size(c)
167
+ cy = (c["top"] + c["bottom"]) / 2
168
+ gx, gy = int(c["x0"] // cell), int(c["top"] // cell)
169
+ found = False
170
+ for dx in (-1, 0, 1):
171
+ for dy in (-1, 0, 1):
172
+ for n in grid.get((gx + dx, gy + dy), ()):
173
+ if n is c or _size(n) < 1.25 * sz:
174
+ continue
175
+ if _hgap(c, n) > 0.5 * sz:
176
+ continue
177
+ if n["top"] <= cy <= n["bottom"]:
178
+ found = True
179
+ break
180
+ if found:
181
+ break
182
+ if found:
183
+ break
184
+ if found:
185
+ out.add(id(c))
186
+ return out
187
+
188
+
189
+ def cluster_leaf_lines(chars: Sequence[dict], body_size: float = 0.0,
190
+ use_body_tol: bool = True,
191
+ attach_small: bool = True) -> List[List[dict]]:
192
+ """Cluster the chars of one XY-cut leaf into lines (each sorted by x0).
193
+
194
+ * Baseline tolerance is ``BASELINE_RANGE`` times the smaller of the page
195
+ body size and the leaf's own dominant size, rather than the leaf mean,
196
+ so one big title glyph does not coarsen the tolerance for the body.
197
+ * Chars much smaller than the leaf's dominant size (superscripts,
198
+ subscripts, footnote marks) are clustered afterwards and attached to the
199
+ nearest line, instead of forming stray lines or splitting a line.
200
+ """
201
+ chars = [c for c in chars if c.get("text", "").strip()]
202
+ if not chars:
203
+ return []
204
+ leaf_mode = mode_size(chars)
205
+ if use_body_tol and body_size > 0 and leaf_mode > 0:
206
+ ref = min(body_size, leaf_mode)
207
+ else:
208
+ ref = statistics.fmean(_size(c) for c in chars)
209
+ tol = BASELINE_RANGE * max(ref, 1.0)
210
+
211
+ small: List[dict] = []
212
+ main = chars
213
+ if attach_small and leaf_mode > 0:
214
+ cut = SMALL_RATIO * leaf_mode
215
+ local = _local_small(chars)
216
+ small = [c for c in chars if _size(c) < cut or id(c) in local]
217
+ main = [c for c in chars if not (_size(c) < cut or id(c) in local)]
218
+ if not main:
219
+ main, small = chars, []
220
+
221
+ lines = _cluster_by_baseline(main, tol)
222
+ if small:
223
+ leftover = _attach_small(lines, small)
224
+ if leftover:
225
+ small_ref = max(statistics.fmean(_size(c) for c in leftover), 1.0)
226
+ lines.extend(_cluster_by_baseline(leftover, BASELINE_RANGE * small_ref))
227
+
228
+ def key(ln):
229
+ return statistics.fmean(c["bottom"] for c in ln)
230
+
231
+ lines.sort(key=key)
232
+ return [line_order(ln) for ln in lines]
233
+
234
+
235
+ # ---------------------------------------------------------------------------
236
+ # words
237
+ # ---------------------------------------------------------------------------
238
+
239
+ def chars_to_words(line_chars: Sequence[dict], x_tol: float,
240
+ space_xs: Sequence[float] = ()) -> List[dict]:
241
+ """Split one line's chars (any order) into word dicts.
242
+
243
+ A word break falls between two chars when the gap exceeds ``x_tol`` or
244
+ when a space glyph (given by its centre x in ``space_xs``) sits between
245
+ their centres.
246
+
247
+ Word geometry (top/bottom) and size come from the line's main-size chars,
248
+ so an attached superscript does not inflate the word box.
249
+ """
250
+ chars = line_order([c for c in line_chars if c.get("text", "")])
251
+ if not chars:
252
+ return []
253
+ groups: List[List[dict]] = []
254
+ cur = [chars[0]]
255
+ right = chars[0]["x1"]
256
+ prev = chars[0]
257
+ spaces = sorted(space_xs)
258
+ line_mode = mode_size(chars)
259
+ small_cut = SMALL_RATIO * line_mode
260
+ for c in chars[1:]:
261
+ has_space = False
262
+ if spaces:
263
+ lo = (prev["x0"] + prev["x1"]) / 2
264
+ hi = (c["x0"] + c["x1"]) / 2
265
+ i = bisect.bisect_right(spaces, lo)
266
+ has_space = i < len(spaces) and spaces[i] <= hi
267
+ # A small raised/lowered run stays on the line but is its own word,
268
+ # so "Me-1" followed by a superscript "100" does not fuse to "Me-1100".
269
+ size_flip = (_size(prev) < small_cut) != (_size(c) < small_cut)
270
+ prev_x0 = prev["x0"]
271
+ prev = c
272
+ backwards = c["x1"] < prev_x0 - x_tol
273
+ if c["x0"] - right > x_tol or has_space or size_flip or backwards:
274
+ groups.append(cur)
275
+ cur = [c]
276
+ right = c["x1"]
277
+ else:
278
+ cur.append(c)
279
+ right = max(right, c["x1"])
280
+ groups.append(cur)
281
+
282
+ words = []
283
+ for g in groups:
284
+ main = [c for c in g if _size(c) >= SMALL_RATIO * line_mode] or g
285
+ fonts = [c["fontname"] for c in main if c.get("fontname")]
286
+ words.append({
287
+ "text": "".join(c["text"] for c in g),
288
+ "x0": min(c["x0"] for c in g),
289
+ "x1": max(c["x1"] for c in g),
290
+ "top": min(c["top"] for c in main),
291
+ "bottom": max(c["bottom"] for c in main),
292
+ "size": mode_size(main) or _size(main[0]),
293
+ "fontname": max(set(fonts), key=fonts.count) if fonts else "",
294
+ })
295
+ return words
296
+
297
+
298
+ def _index_spaces(spaces: Sequence[dict]) -> Dict[int, List[dict]]:
299
+ idx: Dict[int, List[dict]] = {}
300
+ for s in spaces:
301
+ idx.setdefault(int(((s["top"] + s["bottom"]) / 2) // 4), []).append(s)
302
+ return idx
303
+
304
+
305
+ def _line_space_xs(line: Sequence[dict], idx: Dict[int, List[dict]],
306
+ used: set) -> List[float]:
307
+ """Centre x of every unused space glyph lying inside the line's box."""
308
+ if not idx:
309
+ return []
310
+ top = min(c["top"] for c in line)
311
+ bottom = max(c["bottom"] for c in line)
312
+ x0 = min(c["x0"] for c in line)
313
+ x1 = max(c["x1"] for c in line)
314
+ lsize = mode_size(line) or (bottom - top)
315
+ xs = []
316
+ for key in range(int(top // 4), int(bottom // 4) + 1):
317
+ for s in idx.get(key, ()):
318
+ if id(s) in used:
319
+ continue
320
+ cy = (s["top"] + s["bottom"]) / 2
321
+ cx = (s["x0"] + s["x1"]) / 2
322
+ if not (top <= cy <= bottom and x0 <= cx <= x1):
323
+ continue
324
+ # the space must belong to this line: similar size and mostly
325
+ # inside its box (blank filler runs in another size overlap
326
+ # neighbouring lines and must not cut their words)
327
+ sh = max(s["bottom"] - s["top"], 0.1)
328
+ inside = min(s["bottom"], bottom) - max(s["top"], top)
329
+ if inside < 0.6 * sh:
330
+ continue
331
+ ss = _size(s)
332
+ if lsize > 0 and not (0.75 <= ss / lsize <= 1.34):
333
+ continue
334
+ used.add(id(s))
335
+ xs.append(cx)
336
+ return xs
337
+
338
+
339
+ def is_rotated(c: dict) -> bool:
340
+ """True for a char drawn along a vertical (or otherwise rotated) baseline."""
341
+ if not c.get("upright", True):
342
+ return True
343
+ m = c.get("matrix")
344
+ return bool(m) and abs(m[1]) > abs(m[0]) + 1e-6
345
+
346
+
347
+ def drop_duplicate_words(words: Sequence[dict]) -> List[dict]:
348
+ """Drop a word that repeats an earlier word of the line on top of it.
349
+
350
+ Overprinted text (shadows, fake bold with a large offset) yields the same
351
+ word twice in nearly the same place. Same text and at least half of the
352
+ narrower box overlapping horizontally and vertically means a duplicate.
353
+ """
354
+ kept: List[dict] = []
355
+ for w in words:
356
+ dup = False
357
+ for k in kept:
358
+ if k["text"] != w["text"]:
359
+ continue
360
+ ox = min(k["x1"], w["x1"]) - max(k["x0"], w["x0"])
361
+ oy = min(k["bottom"], w["bottom"]) - max(k["top"], w["top"])
362
+ if (ox >= 0.5 * min(k["x1"] - k["x0"], w["x1"] - w["x0"])
363
+ and oy >= 0.5 * min(k["bottom"] - k["top"], w["bottom"] - w["top"])):
364
+ dup = True
365
+ break
366
+ if not dup:
367
+ kept.append(w)
368
+ return kept
369
+
370
+
371
+ def split_rotated(chars: Sequence[dict], min_ratio: float = 3.0
372
+ ) -> Tuple[List[dict], List[dict]]:
373
+ """Separate rotated chars (axis labels, sidebars) from upright text.
374
+
375
+ Rotated chars cannot be clustered into horizontal lines. They are split
376
+ off only when upright text clearly dominates the page (a page that is
377
+ entirely rotated is left alone). Returns (upright chars, rotated chars).
378
+ """
379
+ rot = [c for c in chars if c.get("text", "").strip() and is_rotated(c)]
380
+ if not rot:
381
+ return list(chars), []
382
+ rot_ids = {id(c) for c in rot}
383
+ up = [c for c in chars if id(c) not in rot_ids]
384
+ if sum(1 for c in up if c.get("text", "").strip()) < min_ratio * len(rot):
385
+ return list(chars), []
386
+ return up, rot
387
+
388
+
389
+ def rotated_word_lines(chars: Sequence[dict], x_tol: float,
390
+ first_region: int = 1_000_000
391
+ ) -> Tuple[List[List[dict]], List[int]]:
392
+ """Build whole words from rotated chars, one line per vertical strip.
393
+
394
+ Chars are grouped into strips by their x centre; inside a strip they are
395
+ read along the strip (bottom to top when the text matrix points up, else
396
+ top to bottom) and split into words at gaps wider than ``x_tol``. Each
397
+ strip becomes one line with its own region id, so it never merges with
398
+ upright blocks. Strips are ordered left to right.
399
+ """
400
+ chars = [c for c in chars if c.get("text", "").strip()]
401
+ if not chars:
402
+ return [], []
403
+ chars = sorted(chars, key=lambda c: (c["x0"] + c["x1"]) / 2)
404
+ strips: List[List[dict]] = [[chars[0]]]
405
+ for c in chars[1:]:
406
+ cur = strips[-1]
407
+ mean_x = sum((k["x0"] + k["x1"]) / 2 for k in cur) / len(cur)
408
+ if abs((c["x0"] + c["x1"]) / 2 - mean_x) <= 0.6 * max(_size(c), 1.0):
409
+ cur.append(c)
410
+ else:
411
+ strips.append([c])
412
+ lines, ids = [], []
413
+ for k, st in enumerate(strips):
414
+ m = st[0].get("matrix")
415
+ up = (m[1] > 0) if m else True
416
+ st = sorted(st, key=lambda c: -c["bottom"] if up else c["top"])
417
+ groups, cur = [], [st[0]]
418
+ prev = st[0]
419
+ for c in st[1:]:
420
+ gap = (prev["top"] - c["bottom"]) if up else (c["top"] - prev["bottom"])
421
+ if gap > x_tol:
422
+ groups.append(cur)
423
+ cur = [c]
424
+ else:
425
+ cur.append(c)
426
+ prev = c
427
+ groups.append(cur)
428
+ words = []
429
+ for g in groups:
430
+ fonts = [c["fontname"] for c in g if c.get("fontname")]
431
+ words.append({
432
+ "text": "".join(c["text"] for c in g),
433
+ "x0": min(c["x0"] for c in g), "x1": max(c["x1"] for c in g),
434
+ "top": min(c["top"] for c in g), "bottom": max(c["bottom"] for c in g),
435
+ "size": mode_size(g) or _size(g[0]),
436
+ "fontname": max(set(fonts), key=fonts.count) if fonts else "",
437
+ })
438
+ lines.append(words)
439
+ ids.append(first_region + k)
440
+ return lines, ids
441
+
442
+
443
+ def build_word_lines(leaves: Sequence[Sequence[dict]], x_tol: float,
444
+ body_size: float = 0.0, flags: Optional[dict] = None,
445
+ regions: Optional[Sequence[int]] = None,
446
+ spaces: Sequence[dict] = ()
447
+ ) -> Tuple[List[List[dict]], List[int]]:
448
+ """Leaves of chars -> (word lines, region id per line), in reading order.
449
+
450
+ ``regions`` gives the column region of each leaf (default: leaf index).
451
+ ``spaces`` are the page's space glyphs; they are not part of the XY-cut
452
+ leaves, so each is matched to the single line whose box contains it and
453
+ used as a word break.
454
+ """
455
+ sp_idx = _index_spaces(spaces)
456
+ used: set = set()
457
+ flags = FLAGS if flags is None else flags
458
+ word_lines: List[List[dict]] = []
459
+ leaf_ids: List[int] = []
460
+ for li, leaf in enumerate(leaves):
461
+ i = regions[li] if regions is not None else li
462
+ for ln in cluster_leaf_lines(leaf, body_size,
463
+ use_body_tol=flags.get("body_tol", True),
464
+ attach_small=flags.get("sup", True)):
465
+ words = drop_duplicate_words(
466
+ chars_to_words(ln, x_tol, _line_space_xs(ln, sp_idx, used)))
467
+ if words:
468
+ word_lines.append(words)
469
+ leaf_ids.append(i)
470
+ return word_lines, leaf_ids
471
+
472
+
473
+ # ---------------------------------------------------------------------------
474
+ # hyphenation
475
+ # ---------------------------------------------------------------------------
476
+
477
+ _WORD_RE = re.compile(r"[^\W\d_]+(?:-[^\W\d_]+)*", re.UNICODE)
478
+ _TRAIL_RE = re.compile(r"([^\W\d_]{2,})-$", re.UNICODE)
479
+ _LEAD_RE = re.compile(r"^([a-zß-ÿ]+)(.*)$", re.UNICODE | re.DOTALL)
480
+
481
+
482
+ def page_vocab(texts: Sequence[str]) -> set:
483
+ """Lower-cased hyphen-aware word forms seen in the given line texts."""
484
+ vocab = set()
485
+ for t in texts:
486
+ for m in _WORD_RE.finditer(t):
487
+ vocab.add(m.group(0).lower())
488
+ return vocab
489
+
490
+
491
+ _SENT_END_RE = re.compile(r"[.!?:;…)\]\"”]\s*$")
492
+
493
+
494
+ def continues_paragraph(prev_text: str, curr_text: str) -> bool:
495
+ """True when ``curr_text`` reads as the continuation of ``prev_text``.
496
+
497
+ Used at a column jump: a paragraph that runs from the bottom of one column
498
+ to the top of the next ends its last line mid-sentence (no sentence-final
499
+ punctuation, or a hyphen) and the next line starts in lowercase.
500
+ """
501
+ prev_text = prev_text.rstrip()
502
+ curr_text = curr_text.lstrip()
503
+ if not prev_text or not curr_text:
504
+ return False
505
+ if not curr_text[0].islower():
506
+ return False
507
+ if len(prev_text.split()) < 3:
508
+ return False
509
+ return not _SENT_END_RE.search(prev_text)
510
+
511
+
512
+ def join_lines(texts: Sequence[str], vocab: Optional[set] = None) -> str:
513
+ """Join the lines of a block, repairing words hyphenated at line ends.
514
+
515
+ A line ending in ``letters-`` followed by a line starting in lowercase is
516
+ a candidate. The hyphen is dropped and the halves joined when the joined
517
+ form is a word seen elsewhere on the page, or when the hyphenated form is
518
+ not (so true compounds like "long-term" survive). If the page offers no
519
+ evidence either way, the hyphen is kept and the space removed
520
+ ("informa-tion"), which never loses a token compared with the old output.
521
+ """
522
+ if not texts:
523
+ return ""
524
+ vocab = vocab or set()
525
+ out = texts[0]
526
+ for nxt in texts[1:]:
527
+ m = _TRAIL_RE.search(out)
528
+ n = _LEAD_RE.match(nxt)
529
+ if m and n and not out.endswith("--"):
530
+ left = m.group(1).lower()
531
+ right = n.group(1).lower()
532
+ joined = left + right
533
+ hyph = left + "-" + right
534
+ if joined in vocab and hyph not in vocab:
535
+ out = out[:-1] + nxt
536
+ elif hyph in vocab:
537
+ out = out + nxt
538
+ else:
539
+ out = out + nxt
540
+ continue
541
+ out = out + " " + nxt
542
+ return out
543
+
544
+
545
+ # ---------------------------------------------------------------------------
546
+ # overprinted glyphs
547
+ # ---------------------------------------------------------------------------
548
+
549
+ def dedupe_overprinted(chars: Sequence[dict], tolerance: float = 1.0) -> List[dict]:
550
+ """Drop chars drawn twice at (nearly) the same place (fake bold, shadows).
551
+
552
+ Two chars are duplicates when text, fontname and size match and both x0
553
+ and top are within ``tolerance`` points. The first one in stream order
554
+ is kept. Same idea as pdfplumber's Page.dedupe_chars, without needing a
555
+ Page object.
556
+ """
557
+ cell = max(tolerance, 0.5) * 2
558
+ seen: Dict[tuple, List[Tuple[float, float]]] = {}
559
+ out = []
560
+ for c in chars:
561
+ text = c.get("text", "")
562
+ if not text.strip():
563
+ out.append(c)
564
+ continue
565
+ base = (text, c.get("fontname"), round(_size(c), 1))
566
+ x0, top = c["x0"], c["top"]
567
+ gx, gy = int(x0 // cell), int(top // cell)
568
+ dup = False
569
+ for dx in (-1, 0, 1):
570
+ for dy in (-1, 0, 1):
571
+ for px, pt in seen.get(base + (gx + dx, gy + dy), ()):
572
+ if abs(px - x0) <= tolerance and abs(pt - top) <= tolerance:
573
+ dup = True
574
+ break
575
+ if dup:
576
+ break
577
+ if dup:
578
+ break
579
+ if dup:
580
+ continue
581
+ seen.setdefault(base + (gx, gy), []).append((x0, top))
582
+ out.append(c)
583
+ return out
584
+
585
+
586
+ # ---------------------------------------------------------------------------
587
+ # figure / table label separation
588
+ # ---------------------------------------------------------------------------
589
+
590
+ MASK_MIN_AREA = 0.0005 # fraction of page area; smaller shapes are decoration
591
+ IMAGE_MIN_AREA = 0.005
592
+ MASK_MAX_AREA = 0.25 # bigger shapes are panels or backgrounds, not figures
593
+ CLUSTER_GAP = 6.0 # pt; shapes closer than this belong to one cluster
594
+ MIN_TABLE_CELLS = 3
595
+ MIN_CLUSTER_SHAPES = 4
596
+ MIN_NUMERIC_FRACTION = 0.3
597
+ MAX_PROSE_FRACTION = 0.2
598
+ PROSE_RUN = 6
599
+ _NUM_RE = re.compile(r"\d")
600
+ _CAPTION_RE = re.compile(r"^[^A-Za-z]*(fig(ure)?|tab(le)?)\b", re.IGNORECASE)
601
+
602
+
603
+ def _area(b):
604
+ return max(b[2] - b[0], 0.0) * max(b[3] - b[1], 0.0)
605
+
606
+
607
+ def _contains(a, b, slack=1.0):
608
+ return (a[0] - slack <= b[0] and a[1] - slack <= b[1]
609
+ and a[2] + slack >= b[2] and a[3] + slack >= b[3])
610
+
611
+
612
+ def _near(a, b, gap):
613
+ return not (a[2] + gap < b[0] or b[2] + gap < a[0]
614
+ or a[3] + gap < b[1] or b[3] + gap < a[1])
615
+
616
+
617
+ def build_figure_masks(images: Sequence[dict], shapes: Sequence[dict],
618
+ page_w: float, page_h: float,
619
+ body_size: float = 0.0) -> List[dict]:
620
+ """Cluster page graphics into figure/table masks.
621
+
622
+ ``images`` are page.images, ``shapes`` are rects, curves and lines.
623
+ Returns a list of ``{"kind": "image"|"graphic", "boxes": [bbox, ...]}``.
624
+ Huge shapes (backgrounds) and shapes that contain several others (a
625
+ panel around a table) are ignored. Nearby shapes (closer than about one
626
+ body line) are clustered, so the cells and rules of a table or the axes,
627
+ ticks and bars of a plot form one mask; a cluster of 4+ shapes is
628
+ represented by its union box grown by a small margin, so axis tick labels
629
+ just outside the drawing are covered.
630
+ """
631
+ page_area = max(page_w * page_h, 1.0)
632
+ gap = max(CLUSTER_GAP, body_size)
633
+ margin = 0.75 * body_size
634
+
635
+ def box(o):
636
+ return (o["x0"], o["top"], o["x1"], o["bottom"])
637
+
638
+ masks: List[dict] = []
639
+ for o in images:
640
+ b = box(o)
641
+ frac = _area(b) / page_area
642
+ if IMAGE_MIN_AREA <= frac <= MASK_MAX_AREA:
643
+ masks.append({"kind": "image", "boxes": [b]})
644
+
645
+ cand = []
646
+ for o in shapes:
647
+ b = box(o)
648
+ if _area(b) / page_area > MASK_MAX_AREA:
649
+ continue
650
+ if max(b[2] - b[0], b[3] - b[1]) < 1.0:
651
+ continue
652
+ cand.append(b)
653
+ # a shape that fully contains 3+ other shapes is a panel, not a figure
654
+ keep = []
655
+ for i, b in enumerate(cand):
656
+ if _area(b) / page_area >= MASK_MIN_AREA:
657
+ inside = sum(1 for j, o in enumerate(cand) if j != i and _contains(b, o))
658
+ if inside >= MIN_TABLE_CELLS:
659
+ continue
660
+ keep.append(b)
661
+
662
+ parent = list(range(len(keep)))
663
+
664
+ def find(i):
665
+ while parent[i] != i:
666
+ parent[i] = parent[parent[i]]
667
+ i = parent[i]
668
+ return i
669
+
670
+ order = sorted(range(len(keep)), key=lambda i: keep[i][0])
671
+ for a_pos, i in enumerate(order):
672
+ for j in order[a_pos + 1:]:
673
+ if keep[j][0] > keep[i][2] + gap:
674
+ break
675
+ if _near(keep[i], keep[j], gap):
676
+ ri, rj = find(i), find(j)
677
+ if ri != rj:
678
+ parent[ri] = rj
679
+ groups: Dict[int, List[tuple]] = {}
680
+ for i, b in enumerate(keep):
681
+ groups.setdefault(find(i), []).append(b)
682
+ for boxes in groups.values():
683
+ if len(boxes) >= MIN_CLUSTER_SHAPES:
684
+ u = (min(b[0] for b in boxes) - margin, min(b[1] for b in boxes) - margin,
685
+ max(b[2] for b in boxes) + margin, max(b[3] for b in boxes) + margin)
686
+ if _area(u) / page_area > MASK_MAX_AREA:
687
+ continue
688
+ masks.append({"kind": "graphic", "boxes": [u]})
689
+ elif sum(_area(b) for b in boxes) / page_area >= MASK_MIN_AREA:
690
+ masks.append({"kind": "graphic", "boxes": boxes})
691
+ return masks
692
+
693
+
694
+ def _is_numeric_token(t: str) -> bool:
695
+ if not _NUM_RE.search(t):
696
+ return False
697
+ alpha = sum(ch.isalpha() for ch in t)
698
+ return alpha <= max(1, len(t) // 3)
699
+
700
+
701
+ def _prose_fraction(words: Sequence[dict]) -> float:
702
+ """Share of the words that sit in runs of 6+ words on one text row."""
703
+ rows: Dict[int, int] = {}
704
+ for w in words:
705
+ key = int(round((w["top"] + w["bottom"]) / 2 / max(w.get("size", 10), 1)))
706
+ rows[key] = rows.get(key, 0) + 1
707
+ long_words = sum(n for n in rows.values() if n >= PROSE_RUN)
708
+ return long_words / max(len(words), 1)
709
+
710
+
711
+ def split_figure_words(word_lines: Sequence[List[dict]], leaf_ids: Sequence[int],
712
+ masks: Sequence[dict], body_size: float
713
+ ) -> Tuple[list, list, list, list, list, list]:
714
+ """Split word lines into body lines and figure-label lines.
715
+
716
+ A word is a label candidate when its centre lies in a figure mask. The
717
+ candidates of a mask are kept as labels when they look like figure or
718
+ table text (cells of a table with short entries, mostly numeric groups,
719
+ or a few words over an image). Headings (large or bold lines), figure
720
+ and table captions, and prose stay in the body. Nothing is dropped:
721
+ labels only move to separate lines.
722
+
723
+ Returns (body_lines, body_ids, label_lines, label_ids, body_order,
724
+ label_order); the order lists hold each line's index in ``word_lines``.
725
+ """
726
+ if not masks:
727
+ n = len(word_lines)
728
+ return list(word_lines), list(leaf_ids), [], [], list(range(n)), []
729
+
730
+ def mask_of(w):
731
+ cx, cy = (w["x0"] + w["x1"]) / 2, (w["top"] + w["bottom"]) / 2
732
+ for mi, m in enumerate(masks):
733
+ for b in m["boxes"]:
734
+ if b[0] <= cx <= b[2] and b[1] <= cy <= b[3]:
735
+ return mi
736
+ return -1
737
+
738
+ def protected(line):
739
+ text = " ".join(w["text"] for w in line)
740
+ if _CAPTION_RE.match(text):
741
+ return True
742
+ size = max(w.get("size", 0) for w in line)
743
+ if body_size > 0 and size >= 1.3 * body_size:
744
+ return True
745
+ styles = [w.get("fontname", "") for w in line]
746
+ bold = sum(1 for f in styles if re.search(r"bold|black|heavy", f, re.I))
747
+ return bool(styles) and bold > len(styles) / 2 and len(line) <= 8
748
+
749
+ cand: Dict[int, List[dict]] = {}
750
+ per_line: List[List[int]] = []
751
+ for line in word_lines:
752
+ idxs = []
753
+ prot = protected(line)
754
+ for w in line:
755
+ mi = -1 if prot else mask_of(w)
756
+ idxs.append(mi)
757
+ if mi >= 0:
758
+ cand.setdefault(mi, []).append(w)
759
+ per_line.append(idxs)
760
+
761
+ label_masks = set()
762
+ for mi, ws in cand.items():
763
+ toks = [w["text"] for w in ws]
764
+ numeric = sum(1 for t in toks if _is_numeric_token(t)) / max(len(toks), 1)
765
+ if _prose_fraction(ws) > MAX_PROSE_FRACTION:
766
+ continue
767
+ m = masks[mi]
768
+ if m["kind"] == "image":
769
+ ok = len(ws) <= 12 or numeric >= 0.4
770
+ else:
771
+ ok = numeric >= MIN_NUMERIC_FRACTION and len(ws) <= 400
772
+ if ok:
773
+ label_masks.add(mi)
774
+
775
+ body, body_ids, label, label_ids = [], [], [], []
776
+ body_order, label_order = [], []
777
+ for n, (line, lid, idxs) in enumerate(zip(word_lines, leaf_ids, per_line)):
778
+ keep = [w for w, mi in zip(line, idxs) if mi not in label_masks]
779
+ lab = [w for w, mi in zip(line, idxs) if mi in label_masks]
780
+ if keep:
781
+ body.append(keep)
782
+ body_ids.append(lid)
783
+ body_order.append(n)
784
+ if lab:
785
+ label.append(lab)
786
+ label_ids.append(lid)
787
+ label_order.append(n)
788
+ return body, body_ids, label, label_ids, body_order, label_order
src/poster_sentry/p2j/layout_streams.py ADDED
@@ -0,0 +1,1589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stream-order text layout for pdfplumber pages.
2
+
3
+ Glyphs become words, words become lines and lines become blocks, all in
4
+ content-stream order and in one pass each. The blocks are then sorted top
5
+ down and re-ordered by a column aware band rule. There is no page-wide
6
+ statistic anywhere: every tolerance is a fraction of the font size of the
7
+ text it is applied to, except one small absolute baseline tolerance.
8
+
9
+ Public entry point::
10
+
11
+ blocks = ordered_blocks(page, chars=None, repair_interleave=True, info=None)
12
+
13
+ ``page`` is a pdfplumber page (anything with ``chars``, ``bbox`` or
14
+ ``width``/``height``). ``chars`` may be passed to replace ``page.chars``.
15
+ The result is a list of :class:`Block` in reading order. Each block holds
16
+ :class:`Line` objects with ``text``, ``bbox``, dominant ``size`` and a
17
+ ``bold`` flag.
18
+
19
+ Hardening rules on top of the stream rules: a banner above several columns is
20
+ never hopped by a left block that starts below it; a margin label printed
21
+ beside the text it names is read right before that text; wholly bold headings
22
+ of different columns on one row stay separate blocks; the items of a spaced
23
+ bullet list form one block; letter-spaced words are joined; two raised middle
24
+ dots over a letter are a diaeresis.
25
+
26
+ Everything is iterative; bad glyphs (NaN, infinite or missing numbers) are
27
+ skipped and act as word boundaries, they never raise.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ import re
34
+ import unicodedata
35
+ from bisect import bisect_right
36
+ from typing import Dict, List, Optional, Sequence, Tuple
37
+
38
+ __all__ = ["Word", "Line", "Block", "ordered_blocks"]
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Tolerances. All are fractions of a font size unless the name says "PT".
42
+ # ---------------------------------------------------------------------------
43
+ _PAGE_SLOP_PT = 2.0 # glyph origin may sit this far outside the page
44
+ _BASELINE_TOL_PT = 1.0 # the only absolute number: word level baseline shift
45
+ _WORD_GAP = 0.10 # gap above this (fraction of fs) is a visible space
46
+ _BACKSTEP = 0.30 # origin this far behind the previous end restarts a word
47
+ _COINC_ALONG = 0.10 # overprint tolerances, fraction of fs
48
+ _COINC_ACROSS = 0.20
49
+ _ANGLE_TOL = 3.0 # degrees: words/lines of one direction
50
+ _SNAP_DEG = 1.0 # snap text direction to a right angle within this
51
+ _ROW_FRAC = 0.5 # same visual row: baseline within this times size
52
+ _STACK_OVERLAP = 0.1 # words stacked on one another overlap by more than this times L
53
+ _FAR_FRAC = 1.5 # next word may start this far (times L) past the end
54
+ _SIZE_DIFF = 0.05 # blocks: relative size difference limit
55
+ _LEADING = 1.5 # blocks: baseline step limit, times previous size
56
+ _TITLE_JUMP = 0.3 # first line stands alone when the next starts this far right
57
+ _ACCENT_REACH = 0.8 # an accent belongs to a base within this times fs
58
+ _HOP_CAP = 512 # bound on the backwards scan of the band rule
59
+ _SUPERSCRIPT_SIZE = 0.97 # a script word is smaller than this times L
60
+ _HEADING_MAX_LINES = 3 # a heading is at most this many wholly bold lines
61
+ _HEADING_BOLD = 0.95 # a line is wholly bold from this share of its characters
62
+ _HEADING_NEXT_ALNUM = 3 # the regular line after a heading has at least this many letters or digits
63
+ _ROW_SPLIT_GAP = 3.0 # wholly bold lines of one row this far apart (times size) are separate headings
64
+ _BANNER_FRAC = 0.3 # a banner spans at least this share of the text width
65
+ _DOT_RISE = 0.15 # two middle dots this high above a letter (times size) are a diaeresis
66
+ _TRACK_RUN = 6 # a chain of at least this many short pieces can be letter spaced
67
+ _TRACK_SPREAD = 1.5 # tracking gaps stay within this times the smallest typical gap
68
+ _BULLET_LEADING = 2.6 # bullet items of one list may sit this far apart (times size)
69
+ _SIDE_GAP = 6.0 # a side label sits within this times its size left of the text it names
70
+ _SIDE_BELOW = 3.0 # ... and has no text of its own within this times its height below
71
+ _SCRIPT_REACH = 0.5 # a superscript top may pass the line top by this times L
72
+
73
+ # Interleaved stream repair
74
+ _WIDE_LINE_FRAC = 0.6 # lines wider than this fraction of the page are barriers
75
+ _LANE_OVERLAP = 0.5
76
+ _MIN_LANE_LINES = 3
77
+ _MAX_MEAN_RUN = 2.0
78
+ _SHORT_LINE_L = 8.0
79
+ _STEP_OK_FRAC = 0.7
80
+
81
+ _CIDRE = "(cid:"
82
+ _CONTACT = re.compile(r"@\w|orcid|https?://|www\.", re.I)
83
+ _CLOSERS = frozenset(",;.:)]}")
84
+ _BULLET = re.compile(
85
+ r"^(?:[\u2022\u25cf\u25aa\u25a0\u25e6\u25cb\u25c6\u25c7\u2713\u2714\u27a2\u27a4\u25ba\u25b6\u2605\u00b7\u2026]|[-\u2013*]\s)\s*\S")
86
+
87
+ _UNIT = {0.0: (1.0, 0.0), 90.0: (0.0, 1.0), 180.0: (-1.0, 0.0), 270.0: (0.0, -1.0)}
88
+
89
+ # Marker for a real space glyph in the glyph list. ``None`` marks a dropped
90
+ # or invalid glyph (a word boundary that is not a printed space).
91
+ _SPACE = object()
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Output objects
96
+ # ---------------------------------------------------------------------------
97
+ class Word:
98
+ """A word of a line with its page box."""
99
+
100
+ __slots__ = ("text", "x0", "y0", "x1", "y1", "size", "bold")
101
+
102
+
103
+ class Line:
104
+ """A text line: ``text``, ``bbox``, dominant ``size``, ``bold`` flag and ``words``."""
105
+
106
+ __slots__ = ("text", "x0", "y0", "x1", "y1", "size", "bold", "th", "c", "s",
107
+ "v", "px", "py", "up", "dn", "vt", "vb", "us", "ue", "nchar", "nbold",
108
+ "idx", "nwords", "words", "maxsize")
109
+
110
+ @property
111
+ def bbox(self) -> Tuple[float, float, float, float]:
112
+ return (self.x0, self.y0, self.x1, self.y1)
113
+
114
+ @property
115
+ def height(self) -> float:
116
+ return self.y1 - self.y0
117
+
118
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
119
+ return f"Line({self.text!r})"
120
+
121
+
122
+ class Block:
123
+ """A block of consecutive same-size lines of one direction."""
124
+
125
+ __slots__ = ("lines", "x0", "y0", "x1", "y1", "size", "bold", "first_line_height",
126
+ "direction", "seq")
127
+
128
+ @property
129
+ def bbox(self) -> Tuple[float, float, float, float]:
130
+ return (self.x0, self.y0, self.x1, self.y1)
131
+
132
+ @property
133
+ def text(self) -> str:
134
+ return "\n".join(ln.text for ln in self.lines)
135
+
136
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
137
+ return f"Block({self.text[:40]!r}, {len(self.lines)} lines)"
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Internal records
142
+ # ---------------------------------------------------------------------------
143
+ class _Glyph:
144
+ __slots__ = ("ch", "fs", "ox", "oy", "ex", "ey", "th", "c", "s", "up", "dn",
145
+ "bx0", "by0", "bx1", "by1", "bold", "font", "acc", "ascii_acc", "accd",
146
+ "key", "off")
147
+
148
+
149
+ class _Word:
150
+ __slots__ = ("chars", "th", "c", "s", "v", "fs", "ox", "oy", "ex", "ey", "lx", "ly",
151
+ "ue", "up", "dn", "bx0", "by0", "bx1", "by1", "sp", "nb", "n", "tr")
152
+
153
+ @property
154
+ def text(self) -> str:
155
+ return "".join(self.chars)
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Small helpers
160
+ # ---------------------------------------------------------------------------
161
+ def _ang_close(a: float, b: float, tol: float = _ANGLE_TOL) -> bool:
162
+ d = (a - b + 180.0) % 360.0 - 180.0
163
+ return -tol <= d <= tol
164
+
165
+
166
+ _BOLD_PREFIX = re.compile(r"^[A-Z]{6}\+")
167
+ _BOLD_CACHE: Dict[str, bool] = {}
168
+
169
+
170
+ def _is_bold(fontname) -> bool:
171
+ key = fontname if isinstance(fontname, str) else ""
172
+ hit = _BOLD_CACHE.get(key)
173
+ if hit is not None:
174
+ return hit
175
+ name = _BOLD_PREFIX.sub("", key).lower()
176
+ res = ("bold" in name or "heavy" in name or "black" in name
177
+ or name.endswith("-bd") or name.endswith(",bd") or name.endswith("-bdit"))
178
+ if len(_BOLD_CACHE) < 4096:
179
+ _BOLD_CACHE[key] = res
180
+ return res
181
+
182
+
183
+ # Accents. A spacing accent is a modifier symbol whose compatibility
184
+ # decomposition (NFKD of the glyph itself) is a space followed by a combining
185
+ # mark. A few modifier letters have no decomposition at all and get an explicit combining form.
186
+ _NO_DECOMP_ACCENTS = {"\u02c6": "\u0302", "\u02c7": "\u030c"}
187
+ _ASCII_ACCENTS = {"^": "\u0302", "`": "\u0300", "~": "\u0303"}
188
+ _ACCENT_CACHE: Dict[str, Optional[Tuple[str, bool]]] = {}
189
+
190
+
191
+ def _accent_form(ch: str) -> Optional[Tuple[str, bool]]:
192
+ """(combining mark, is_ascii_lookalike) when ``ch`` is an accent glyph."""
193
+ if ch in _ACCENT_CACHE:
194
+ return _ACCENT_CACHE[ch]
195
+ res: Optional[Tuple[str, bool]] = None
196
+ if len(ch) == 1:
197
+ if ch in _ASCII_ACCENTS:
198
+ res = (_ASCII_ACCENTS[ch], True)
199
+ elif unicodedata.category(ch) == "Mn":
200
+ res = (ch, False)
201
+ elif ch in _NO_DECOMP_ACCENTS:
202
+ res = (_NO_DECOMP_ACCENTS[ch], False)
203
+ elif unicodedata.category(ch) == "Sk":
204
+ d = unicodedata.normalize("NFKD", ch)
205
+ if len(d) == 2 and d[0] == " " and unicodedata.category(d[1]) == "Mn":
206
+ res = (d[1], False)
207
+ if len(_ACCENT_CACHE) < 4096:
208
+ _ACCENT_CACHE[ch] = res
209
+ return res
210
+
211
+
212
+ def _compose(base: str, mark: str) -> str:
213
+ if base == "\u0131":
214
+ base = "i"
215
+ out = unicodedata.normalize("NFC", base + mark)
216
+ return out if len(out) == 1 else base + mark
217
+
218
+
219
+ def _finite_sum(*vals: float) -> bool:
220
+ s = 0.0
221
+ for v in vals:
222
+ s += v
223
+ return s - s == 0.0
224
+
225
+
226
+ def _num(v) -> Optional[float]:
227
+ """float(v), or None for missing or non numeric values (NaN is returned)."""
228
+ if v is None or isinstance(v, bool):
229
+ return None
230
+ try:
231
+ return float(v)
232
+ except (TypeError, ValueError, OverflowError):
233
+ return None
234
+
235
+
236
+ # ---------------------------------------------------------------------------
237
+ # Page frame
238
+ # ---------------------------------------------------------------------------
239
+ def _page_frame(page) -> Tuple[float, float, float, float, float, float, float]:
240
+ """(origin x, origin y, width, height, root height, mediabox x0, mediabox top).
241
+
242
+ The first two are the page box origin that is subtracted from every
243
+ coordinate. The last three convert the text matrix (kept by pdfminer
244
+ relative to the media box, y up) to the pdfplumber top-left frame.
245
+ """
246
+ bbox = getattr(page, "bbox", None)
247
+ ox = oy = 0.0
248
+ w = _num(getattr(page, "width", None))
249
+ h = _num(getattr(page, "height", None))
250
+ try:
251
+ if bbox is not None and len(bbox) == 4:
252
+ b = [float(x) for x in bbox]
253
+ if _finite_sum(*b):
254
+ ox, oy = b[0], b[1]
255
+ w, h = b[2] - b[0], b[3] - b[1]
256
+ except (TypeError, ValueError):
257
+ pass
258
+ if w is None or h is None or not _finite_sum(w, h):
259
+ w, h = 0.0, 0.0
260
+ root = getattr(page, "root_page", None) or page
261
+ mbx, mby = ox, oy
262
+ root_h = h
263
+ try:
264
+ mb = getattr(root, "mediabox", None)
265
+ if mb is not None and len(mb) == 4:
266
+ m = [float(x) for x in mb]
267
+ if _finite_sum(*m):
268
+ mbx, mby = m[0], m[1]
269
+ rh = _num(getattr(root, "height", None))
270
+ if rh is not None and _finite_sum(rh) and rh > 0:
271
+ root_h = rh
272
+ except (TypeError, ValueError):
273
+ pass
274
+ return ox, oy, w, h, root_h, mbx, mby
275
+
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # Glyph preparation
279
+ # ---------------------------------------------------------------------------
280
+ def _direction(a: float, b: float, c: float, d: float):
281
+ """(theta degrees in the top-left frame, cos, sin) or None when degenerate."""
282
+ if a * a + b * b < 1e-18:
283
+ a, b = d, -c # reading direction is perpendicular to the up vector
284
+ if a * a + b * b < 1e-18:
285
+ return None
286
+ th = math.degrees(math.atan2(-b, a)) % 360.0
287
+ for snap in (0.0, 90.0, 180.0, 270.0, 360.0):
288
+ if abs(th - snap) <= _SNAP_DEG:
289
+ th = 0.0 if snap == 360.0 else snap
290
+ cs = _UNIT[th]
291
+ return th, cs[0], cs[1]
292
+ r = math.radians(th)
293
+ return th, math.cos(r), math.sin(r)
294
+
295
+
296
+ def _across_from_box(th, c, s, x0, y0, x1, y1):
297
+ """(min v, max v) of a page box in the frame (c, s)."""
298
+ if th == 0.0:
299
+ return y0, y1
300
+ if th == 90.0:
301
+ return -x1, -x0
302
+ if th == 180.0:
303
+ return -y1, -y0
304
+ if th == 270.0:
305
+ return x0, x1
306
+ vs = (-x0 * s + y0 * c, -x1 * s + y0 * c, -x0 * s + y1 * c, -x1 * s + y1 * c)
307
+ return min(vs), max(vs)
308
+
309
+
310
+ def _prepare(page, chars, frame, info) -> list:
311
+ """Glyph records in stream order; ``None`` and ``_SPACE`` are boundaries."""
312
+ ox0, oy0, pw, ph, root_h, mbx, mby = frame
313
+ items: list = []
314
+ use_box_origin = _frame_is_unreliable(chars, frame)
315
+ rise_groups: Dict[str, Dict[float, int]] = {}
316
+ risers: list = []
317
+ dropped = 0
318
+ for ch in chars:
319
+ try:
320
+ g = _make_glyph(ch, ox0, oy0, pw, ph, root_h, mbx, mby, use_box_origin)
321
+ except Exception: # noqa: BLE001 - never raise
322
+ g = None
323
+ if g is None or g is _SPACE:
324
+ if g is None:
325
+ dropped += 1
326
+ items.append(g)
327
+ continue
328
+ if g.key is not None:
329
+ d = rise_groups.setdefault(g.font, {})
330
+ d[g.key] = d.get(g.key, 0) + 1
331
+ risers.append(g)
332
+ items.append(g)
333
+ # Text rise (Ts) moves the glyph box but not the matrix origin. The box
334
+ # offset from the baseline is constant per font, so a deviation from the
335
+ # font's usual offset is a rise.
336
+ if risers:
337
+ mode = {}
338
+ for font, d in rise_groups.items():
339
+ best = max(d.items(), key=lambda kv: (kv[1], -abs(kv[0])))
340
+ mode[font] = best[0]
341
+ for g in risers:
342
+ r = (mode[g.font] - g.off) * g.fs
343
+ if abs(r) > max(0.3, 0.04 * g.fs):
344
+ g.ox += r * g.s
345
+ g.oy -= r * g.c
346
+ g.ex += r * g.s
347
+ g.ey -= r * g.c
348
+ g.up -= r
349
+ g.dn += r
350
+ if info is not None:
351
+ info["dropped_glyphs"] = dropped
352
+ return items
353
+
354
+
355
+ def _frame_is_unreliable(chars, frame) -> bool:
356
+ """True when matrix origins do not sit on the glyph boxes (odd producer or
357
+ a page object that does not follow the pdfplumber frame)."""
358
+ ox0, oy0, pw, ph, root_h, mbx, mby = frame
359
+ ok = bad = 0
360
+ for ch in chars:
361
+ if ok + bad >= 200:
362
+ break
363
+ try:
364
+ m = ch.get("matrix")
365
+ if m is None or len(m) != 6:
366
+ continue
367
+ a, b, c, d, e, f = (float(v) for v in m)
368
+ size = float(ch["size"])
369
+ top = float(ch["top"]) - oy0
370
+ bot = float(ch["bottom"]) - oy0
371
+ if not (_finite_sum(a, b, c, d, e, f, size, top, bot) and size > 0):
372
+ continue
373
+ if abs(b) > 1e-6 * abs(a) or abs(c) > 1e-6 * abs(d) or a <= 0 or d <= 0:
374
+ continue
375
+ yb = (root_h - f) + mby - oy0
376
+ except Exception: # noqa: BLE001
377
+ continue
378
+ if top - 0.5 * size <= yb <= bot + 0.5 * size:
379
+ ok += 1
380
+ else:
381
+ bad += 1
382
+ return (ok + bad) >= 5 and bad > ok
383
+
384
+
385
+ def _make_glyph(ch, ox0, oy0, pw, ph, root_h, mbx, mby, use_box_origin):
386
+ text = ch.get("text")
387
+ if not isinstance(text, str) or not text:
388
+ return None
389
+ if text.startswith(_CIDRE):
390
+ return None
391
+ if text.isspace():
392
+ return _SPACE
393
+
394
+ x0 = ch.get("x0")
395
+ x1 = ch.get("x1")
396
+ top = ch.get("top")
397
+ bot = ch.get("bottom")
398
+ boxv = (x0, x1, top, bot)
399
+ have_box = all(v is not None for v in boxv)
400
+ if not have_box and any(v is not None for v in boxv):
401
+ return None # partial box: invalid
402
+ if have_box:
403
+ x0, x1, top, bot = (_num(v) for v in boxv)
404
+ if x0 is None or x1 is None or top is None or bot is None:
405
+ return None
406
+ if not _finite_sum(x0, x1, top, bot):
407
+ return None
408
+ x0 -= ox0
409
+ x1 -= ox0
410
+ top -= oy0
411
+ bot -= oy0
412
+
413
+ mat = ch.get("matrix")
414
+ have_mat = mat is not None
415
+ a = b = c = d = e = f = 0.0
416
+ if have_mat:
417
+ try:
418
+ if len(mat) != 6:
419
+ return None
420
+ vals = [_num(v) for v in mat]
421
+ except TypeError:
422
+ return None
423
+ if any(v is None for v in vals):
424
+ return None
425
+ a, b, c, d, e, f = vals
426
+ if not _finite_sum(a, b, c, d, e, f):
427
+ return None
428
+ elif not have_box:
429
+ return None
430
+
431
+ size = ch.get("size")
432
+ fs = None
433
+ if size is not None:
434
+ fs = _num(size)
435
+ if fs is None or not _finite_sum(fs):
436
+ return None
437
+ if fs is None or fs <= 0:
438
+ if have_box and bot - top > 0:
439
+ fs = bot - top
440
+ elif have_mat and math.hypot(c, d) > 0:
441
+ fs = math.hypot(c, d)
442
+ else:
443
+ return None
444
+ if fs <= 0:
445
+ return None
446
+
447
+ if not have_mat:
448
+ a, d = 1.0, 1.0 # synthesize upright text
449
+ b = c = 0.0
450
+ dr = _direction(a, b, c, d)
451
+ if dr is None:
452
+ return None
453
+ th, cs, sn = dr
454
+
455
+ # pdfminer reports the page-box height as the size of a glyph. For text
456
+ # reading top to bottom or bottom to top that height is the glyph advance,
457
+ # so every letter gets a different size. The box width is the font size.
458
+ if have_box and (th == 90.0 or th == 270.0) and x1 - x0 > 0:
459
+ if abs((x1 - x0) - fs) > 0.05 * max(x1 - x0, fs):
460
+ fs = x1 - x0
461
+
462
+ # Origin in the normalized top-left frame.
463
+ if have_mat and not use_box_origin:
464
+ px = e + mbx - ox0
465
+ py = (root_h - f) + mby - oy0
466
+ elif have_box:
467
+ px, py = _origin_from_box(th, x0, x1, top, bot, fs)
468
+ else:
469
+ return None
470
+ if not (-_PAGE_SLOP_PT <= px <= pw + _PAGE_SLOP_PT
471
+ and -_PAGE_SLOP_PT <= py <= ph + _PAGE_SLOP_PT):
472
+ return None # hidden text
473
+
474
+ # Advance along the reading direction.
475
+ scale = math.hypot(a, b) if have_mat else 1.0
476
+ adv = _num(ch.get("adv"))
477
+ sheared = False
478
+ if have_mat:
479
+ cd = math.hypot(c, d)
480
+ if cd > 0 and abs(a * c + b * d) > 0.05 * scale * cd:
481
+ sheared = True
482
+ if adv is not None and _finite_sum(adv) and adv >= 0 and have_mat:
483
+ length = adv * scale
484
+ if length <= 0 and have_box:
485
+ length = _box_advance(th, cs, sn, x0, x1, top, bot, fs)
486
+ elif have_box:
487
+ length = _box_advance(th, cs, sn, x0, x1, top, bot, fs)
488
+ if sheared and abs(d) > 0:
489
+ length = max(0.0, length - abs(c / d) * fs)
490
+ else:
491
+ length = 0.5 * fs
492
+
493
+ # Box and across offsets.
494
+ if have_box and not sheared:
495
+ bx0, by0, bx1, by1 = x0, top, x1, bot
496
+ vt, vb = _across_from_box(th, cs, sn, bx0, by0, bx1, by1)
497
+ v0 = -px * sn + py * cs
498
+ up = v0 - vt
499
+ dn = vb - v0
500
+ if up + dn <= 0.0:
501
+ up, dn = 0.75 * fs, 0.25 * fs
502
+ bx0, by0, bx1, by1 = _synth_box(px, py, cs, sn, length, up, dn)
503
+ else:
504
+ up, dn = 0.75 * fs, 0.25 * fs
505
+ bx0, by0, bx1, by1 = _synth_box(px, py, cs, sn, length, up, dn)
506
+
507
+ g = _Glyph()
508
+ g.ch = text
509
+ g.fs = fs
510
+ g.ox = px
511
+ g.oy = py
512
+ g.ex = px + length * cs
513
+ g.ey = py + length * sn
514
+ g.th = th
515
+ g.c = cs
516
+ g.s = sn
517
+ g.up = up
518
+ g.dn = dn
519
+ g.bx0 = bx0
520
+ g.by0 = by0
521
+ g.bx1 = bx1
522
+ g.by1 = by1
523
+ font = ch.get("fontname")
524
+ g.font = font if isinstance(font, str) else ""
525
+ g.bold = _is_bold(g.font)
526
+ acc = _accent_form(text)
527
+ g.acc = acc[0] if acc else None
528
+ g.ascii_acc = bool(acc and acc[1])
529
+ g.accd = False
530
+ if have_box and not sheared and have_mat and not use_box_origin:
531
+ g.key = round(dn / fs, 3)
532
+ g.off = dn / fs
533
+ else:
534
+ g.key = None
535
+ g.off = 0.0
536
+ return g
537
+
538
+
539
+ def _origin_from_box(th, x0, x1, top, bot, fs):
540
+ """Origin estimated from a glyph box (ascent 0.75, descent 0.25)."""
541
+ if th == 0.0:
542
+ return x0, bot - 0.25 * fs
543
+ if th == 90.0:
544
+ return x0 + 0.25 * fs, top
545
+ if th == 180.0:
546
+ return x1, top + 0.25 * fs
547
+ if th == 270.0:
548
+ return x1 - 0.25 * fs, bot
549
+ return x0, bot - 0.25 * fs
550
+
551
+
552
+ def _box_advance(th, cs, sn, x0, x1, top, bot, fs):
553
+ if th == 0.0 or th == 180.0:
554
+ return max(0.0, x1 - x0)
555
+ if th == 90.0 or th == 270.0:
556
+ return max(0.0, bot - top)
557
+ w = x1 - x0
558
+ h = bot - top
559
+ return max(0.0, w * abs(cs) + h * abs(sn) - 2.0 * fs * abs(sn) * abs(cs))
560
+
561
+
562
+ def _synth_box(px, py, cs, sn, length, up, dn):
563
+ """Page box of a glyph rectangle given by origin, advance and offsets."""
564
+ pts = []
565
+ for u in (0.0, length):
566
+ for v in (-up, dn):
567
+ pts.append((px + u * cs - v * sn, py + u * sn + v * cs))
568
+ xs = [p[0] for p in pts]
569
+ ys = [p[1] for p in pts]
570
+ return min(xs), min(ys), max(xs), max(ys)
571
+
572
+
573
+ # ---------------------------------------------------------------------------
574
+ # Overprints
575
+ # ---------------------------------------------------------------------------
576
+ _LEVEL_CELL: Dict[int, float] = {}
577
+
578
+
579
+ def _drop_overprints(items: list) -> list:
580
+ """Remove glyphs that repeat an earlier glyph at (almost) the same origin."""
581
+ grid: Dict[tuple, list] = {}
582
+ out: list = []
583
+ log2 = math.log2
584
+ floor = math.floor
585
+ for g in items:
586
+ if g is None or g is _SPACE:
587
+ out.append(g)
588
+ continue
589
+ fs = g.fs
590
+ lv = log2(fs) * 2.0 + 0.5
591
+ k = int(floor(lv))
592
+ frac = lv - k
593
+ levels = (k,)
594
+ if frac < 0.06:
595
+ levels = (k, k - 1)
596
+ elif frac > 0.94:
597
+ levels = (k, k + 1)
598
+ dup = False
599
+ ch = g.ch
600
+ gx, gy = g.ox, g.oy
601
+ for kk in levels:
602
+ cell = _LEVEL_CELL.get(kk)
603
+ if cell is None:
604
+ cell = 0.5 * 2.0 ** (kk / 2.0)
605
+ _LEVEL_CELL[kk] = cell
606
+ ix = int(floor(gx / cell))
607
+ iy = int(floor(gy / cell))
608
+ for dx in (-1, 0, 1):
609
+ for dy in (-1, 0, 1):
610
+ lst = grid.get((kk, ix + dx, iy + dy))
611
+ if not lst:
612
+ continue
613
+ for h in lst:
614
+ if h.ch != ch or h.font != g.font:
615
+ continue
616
+ if abs(h.fs - fs) > 0.02 * max(h.fs, fs):
617
+ continue
618
+ if not _ang_close(h.th, g.th, 1.0):
619
+ continue
620
+ rx = gx - h.ox
621
+ ry = gy - h.oy
622
+ du = rx * h.c + ry * h.s
623
+ dv = -rx * h.s + ry * h.c
624
+ if abs(du) <= _COINC_ALONG * fs and abs(dv) <= _COINC_ACROSS * fs:
625
+ dup = True
626
+ break
627
+ if dup:
628
+ break
629
+ if dup:
630
+ break
631
+ if dup:
632
+ break
633
+ if dup:
634
+ continue
635
+ cell = _LEVEL_CELL.get(k)
636
+ if cell is None:
637
+ cell = 0.5 * 2.0 ** (k / 2.0)
638
+ _LEVEL_CELL[k] = cell
639
+ key = (k, int(floor(gx / cell)), int(floor(gy / cell)))
640
+ lst = grid.get(key)
641
+ if lst is None:
642
+ grid[key] = [g]
643
+ else:
644
+ lst.append(g)
645
+ out.append(g)
646
+ return out
647
+
648
+
649
+ # ---------------------------------------------------------------------------
650
+ # Accents
651
+ # ---------------------------------------------------------------------------
652
+ def _is_base(h) -> bool:
653
+ return (isinstance(h, _Glyph) and h.acc is None and len(h.ch) == 1
654
+ and (h.ch.isalpha() or h.ch == "\u0131"))
655
+
656
+
657
+ def _accent_dist(a: _Glyph, h: _Glyph) -> Optional[float]:
658
+ """Horizontal distance between accent a and base h along h's reading
659
+ direction, or None when a cannot belong to h."""
660
+ if not _ang_close(a.th, h.th):
661
+ return None
662
+ c, s = h.c, h.s
663
+ ua0 = a.ox * c + a.oy * s
664
+ ua1 = a.ex * c + a.ey * s
665
+ if ua1 < ua0:
666
+ ua0, ua1 = ua1, ua0
667
+ uh0 = h.ox * c + h.oy * s
668
+ uh1 = h.ex * c + h.ey * s
669
+ if uh1 < uh0:
670
+ uh0, uh1 = uh1, uh0
671
+ va = -a.ox * s + a.oy * c
672
+ vh = -h.ox * s + h.oy * c
673
+ if abs(va - vh) > h.fs:
674
+ return None
675
+ gap = max(0.0, ua0 - uh1, uh0 - ua1)
676
+ if gap > _ACCENT_REACH * h.fs:
677
+ return None
678
+ if a.ascii_acc:
679
+ width = ua1 - ua0
680
+ overlap = min(ua1, uh1) - max(ua0, uh0)
681
+ if width <= 0 or overlap <= width / 3.0:
682
+ return None
683
+ return abs((ua0 + ua1) / 2.0 - (uh0 + uh1) / 2.0)
684
+
685
+
686
+ def _dot_pairs(items: list) -> list:
687
+ """Two raised middle dots over a letter are one diaeresis.
688
+
689
+ Some fonts draw the diaeresis as two separate "middle dot" glyphs that sit
690
+ above the letter and come before or after it in the stream. The pair is
691
+ turned into one spacing diaeresis, which ``_merge_accents`` then folds into
692
+ the letter it sits over.
693
+ """
694
+ out: list = []
695
+ n = len(items)
696
+ i = 0
697
+ while i < n:
698
+ g = items[i]
699
+ h = items[i + 1] if i + 1 < n else None
700
+ if (isinstance(g, _Glyph) and isinstance(h, _Glyph) and g.ch == "·" and h.ch == "·"
701
+ and g.acc is None and h.acc is None and _ang_close(g.th, h.th)):
702
+ nxt = items[i + 2] if i + 2 < n else None
703
+ c, sn = g.c, g.s
704
+ u0 = min(g.ox * c + g.oy * sn, h.ox * c + h.oy * sn)
705
+ u1 = max(g.ex * c + g.ey * sn, h.ex * c + h.ey * sn)
706
+ mid = (u0 + u1) / 2.0
707
+ vd = -g.ox * sn + g.oy * c
708
+ for base in (nxt, out[-1] if out else None):
709
+ if not _is_base(base) or not _ang_close(base.th, g.th):
710
+ continue
711
+ b0 = base.ox * c + base.oy * sn
712
+ b1 = base.ex * c + base.ey * sn
713
+ if b1 < b0:
714
+ b0, b1 = b1, b0
715
+ vb = -base.ox * sn + base.oy * c
716
+ if b0 <= mid <= b1 and vb - vd > _DOT_RISE * base.fs:
717
+ g.ch = "¨"
718
+ g.acc = "̈"
719
+ g.ascii_acc = False
720
+ g.ex, g.ey = h.ex, h.ey
721
+ out.append(g)
722
+ i += 2
723
+ break
724
+ else:
725
+ out.append(g)
726
+ i += 1
727
+ continue
728
+ out.append(g)
729
+ i += 1
730
+ return out
731
+
732
+
733
+ def _merge_accents(items: list) -> list:
734
+ """Fold spacing accents and combining marks into the base letter."""
735
+ out: list = []
736
+ n = len(items)
737
+ i = 0
738
+ while i < n:
739
+ g = items[i]
740
+ if g is None or g is _SPACE or g.acc is None:
741
+ out.append(g)
742
+ i += 1
743
+ continue
744
+ prev = out[-1] if out else None
745
+ j = i + 1
746
+ while j < n and isinstance(items[j], _Glyph) and items[j].acc is not None:
747
+ j += 1
748
+ nxt = items[j] if j < n else None
749
+ dp = _accent_dist(g, prev) if _is_base(prev) else None
750
+ dn = _accent_dist(g, nxt) if _is_base(nxt) else None
751
+ target = None
752
+ if dp is not None and dn is not None:
753
+ if g.ch and unicodedata.category(g.ch) == "Mn":
754
+ target = prev
755
+ else:
756
+ target = nxt if dn <= dp else prev
757
+ elif dp is not None:
758
+ target = prev
759
+ elif dn is not None:
760
+ target = nxt
761
+ if target is None:
762
+ out.append(g) # stands alone
763
+ elif not target.accd:
764
+ target.ch = _compose(target.ch, g.acc)
765
+ target.accd = True
766
+ # else: a second accent on the same base is ignored
767
+ i += 1
768
+ return out
769
+
770
+
771
+ # ---------------------------------------------------------------------------
772
+ # Glyphs to words
773
+ # ---------------------------------------------------------------------------
774
+ def _new_word(g: _Glyph) -> _Word:
775
+ w = _Word()
776
+ w.chars = [g.ch]
777
+ w.th = g.th
778
+ w.c = g.c
779
+ w.s = g.s
780
+ w.v = -g.ox * g.s + g.oy * g.c
781
+ w.fs = g.fs
782
+ w.ox = g.ox
783
+ w.oy = g.oy
784
+ w.ex = g.ex
785
+ w.ey = g.ey
786
+ w.lx = g.ox
787
+ w.ly = g.oy
788
+ w.ue = g.ex * g.c + g.ey * g.s
789
+ w.up = g.up
790
+ w.dn = g.dn
791
+ w.bx0 = g.bx0
792
+ w.by0 = g.by0
793
+ w.bx1 = g.bx1
794
+ w.by1 = g.by1
795
+ w.sp = False
796
+ w.tr = -1.0
797
+ w.n = len(g.ch)
798
+ w.nb = w.n if g.bold else 0
799
+ return w
800
+
801
+
802
+ def _build_words(items: list) -> List[_Word]:
803
+ words: List[_Word] = []
804
+ cur: Optional[_Word] = None
805
+ for g in items:
806
+ if g is _SPACE:
807
+ if cur is not None:
808
+ cur.sp = True
809
+ cur = None
810
+ elif words:
811
+ words[-1].sp = True
812
+ continue
813
+ if g is None: # dropped or invalid glyph: word boundary
814
+ if cur is not None:
815
+ cur.sp = True
816
+ cur = None
817
+ elif words:
818
+ words[-1].sp = True
819
+ continue
820
+ if cur is not None:
821
+ if g.th != cur.th and not _ang_close(g.th, cur.th):
822
+ cur = None
823
+ else:
824
+ cc = cur.c
825
+ ss = cur.s
826
+ u = g.ox * cc + g.oy * ss
827
+ v = -g.ox * ss + g.oy * cc
828
+ fs = cur.fs
829
+ gap = u - cur.ue
830
+ if gap > _WORD_GAP * fs:
831
+ cur.sp = True
832
+ cur.tr = gap / fs # gap that split the words (no space glyph)
833
+ cur = None
834
+ elif gap < -_BACKSTEP * fs:
835
+ cur = None
836
+ elif abs(v - cur.v) > _BASELINE_TOL_PT:
837
+ cur = None
838
+ else:
839
+ rx = g.ox - cur.lx
840
+ ry = g.oy - cur.ly
841
+ du = rx * cc + ry * ss
842
+ dv = -rx * ss + ry * cc
843
+ if abs(du) <= _COINC_ALONG * fs and abs(dv) <= _COINC_ACROSS * fs:
844
+ cur = None
845
+ if cur is None:
846
+ cur = _new_word(g)
847
+ words.append(cur)
848
+ continue
849
+ cur.chars.append(g.ch)
850
+ cur.n += len(g.ch)
851
+ if g.bold:
852
+ cur.nb += len(g.ch)
853
+ cur.ex = g.ex
854
+ cur.ey = g.ey
855
+ cur.lx = g.ox
856
+ cur.ly = g.oy
857
+ cur.ue = g.ex * cc + g.ey * ss
858
+ if g.up > cur.up:
859
+ cur.up = g.up
860
+ if g.dn > cur.dn:
861
+ cur.dn = g.dn
862
+ if g.bx0 < cur.bx0:
863
+ cur.bx0 = g.bx0
864
+ if g.by0 < cur.by0:
865
+ cur.by0 = g.by0
866
+ if g.bx1 > cur.bx1:
867
+ cur.bx1 = g.bx1
868
+ if g.by1 > cur.by1:
869
+ cur.by1 = g.by1
870
+ return _join_tracked(words)
871
+
872
+
873
+ def _join_tracked(words: List[_Word]) -> List[_Word]:
874
+ """Glue letter-spaced text back into words.
875
+
876
+ Tracked text has a small, even gap between letters (it can pass the word
877
+ gap limit, even look like a real space) and a clearly larger gap between
878
+ words. In a chain of at least ``_TRACK_RUN`` short pieces that is split
879
+ only by gaps (never by a space glyph), gaps within ``_TRACK_SPREAD`` of the
880
+ typical small gap are letter gaps, provided the chain also holds a larger
881
+ gap that marks a word boundary. Without such a boundary nothing is joined.
882
+ """
883
+ out: List[_Word] = []
884
+ n = len(words)
885
+ i = 0
886
+ while i < n:
887
+ j = i
888
+ while (j < n - 1 and words[j].tr >= 0 and words[j].n <= 2 and words[j + 1].n <= 2
889
+ and words[j].th == words[j + 1].th):
890
+ j += 1
891
+ if j - i + 1 < _TRACK_RUN:
892
+ out.append(words[i])
893
+ i += 1
894
+ continue
895
+ gaps = sorted(words[k].tr for k in range(i, j))
896
+ g0 = gaps[(len(gaps) - 1) // 4]
897
+ limit = _TRACK_SPREAD * g0
898
+ if gaps[-1] <= limit or g0 <= 0:
899
+ out.extend(words[i:j + 1])
900
+ i = j + 1
901
+ continue
902
+ a = words[i]
903
+ out.append(a)
904
+ for k in range(i + 1, j + 1):
905
+ b = words[k]
906
+ if words[k - 1].tr <= limit:
907
+ a.chars.extend(b.chars)
908
+ a.n += b.n
909
+ a.nb += b.nb
910
+ a.ex, a.ey, a.lx, a.ly, a.ue = b.ex, b.ey, b.lx, b.ly, b.ue
911
+ a.up = max(a.up, b.up)
912
+ a.dn = max(a.dn, b.dn)
913
+ a.bx0, a.by0 = min(a.bx0, b.bx0), min(a.by0, b.by0)
914
+ a.bx1, a.by1 = max(a.bx1, b.bx1), max(a.by1, b.by1)
915
+ a.sp = b.sp
916
+ a.tr = b.tr
917
+ else:
918
+ a = b
919
+ out.append(a)
920
+ i = j + 1
921
+ return out
922
+
923
+
924
+ # ---------------------------------------------------------------------------
925
+ # Words to lines
926
+ # ---------------------------------------------------------------------------
927
+ def _heavy(pairs: List[Tuple[float, float]], prefer_large: bool = True) -> float:
928
+ """Weighted median of (value, weight) pairs."""
929
+ pairs = sorted(pairs, reverse=prefer_large)
930
+ total = sum(w for _, w in pairs)
931
+ half = total / 2.0
932
+ acc = 0.0
933
+ for val, w in pairs:
934
+ acc += w
935
+ if acc >= half:
936
+ return val
937
+ return pairs[-1][0]
938
+
939
+
940
+ def _dominant_baseline(vs: List[Tuple[float, float]]) -> float:
941
+ """Baseline of the heaviest cluster of word baselines (weights n * size)."""
942
+ vs = sorted(vs)
943
+ best_w = -1.0
944
+ best = vs[0][0]
945
+ cluster: List[Tuple[float, float]] = []
946
+ last = None
947
+ for v, w in vs + [(None, 0.0)]:
948
+ if v is None or (last is not None and v - last > _BASELINE_TOL_PT):
949
+ if cluster:
950
+ tw = sum(x for _, x in cluster)
951
+ if tw > best_w:
952
+ best_w = tw
953
+ best = _heavy(cluster)
954
+ cluster = []
955
+ if v is not None:
956
+ cluster.append((v, w))
957
+ last = v
958
+ return best
959
+
960
+
961
+ # ---------------------------------------------------------------------------
962
+ # Right to left words. The content stream of most producers lists Hebrew and
963
+ # Arabic glyphs left to right as they are printed (visual order); the logical
964
+ # text is the reverse.
965
+ # ---------------------------------------------------------------------------
966
+ _MIRROR = str.maketrans("()[]{}<>", ")(][}{><")
967
+
968
+
969
+ def _rtl_classes(texts: List[str]) -> List[str]:
970
+ """'R' for right to left words, 'L' for the rest. A word without letters
971
+ (digits, punctuation) between two right to left words belongs to them."""
972
+ cls = []
973
+ any_r = False
974
+ for t in texts:
975
+ r = l = 0
976
+ for ch in t:
977
+ b = unicodedata.bidirectional(ch)
978
+ if b == "R" or b == "AL":
979
+ r += 1
980
+ elif b == "L":
981
+ l += 1
982
+ if r and r >= l:
983
+ cls.append("R")
984
+ any_r = True
985
+ elif l:
986
+ cls.append("L")
987
+ else:
988
+ cls.append("N")
989
+ if not any_r:
990
+ return ["L"] * len(texts)
991
+ n = len(cls)
992
+ out = list(cls)
993
+ k = 0
994
+ while k < n:
995
+ if cls[k] != "N":
996
+ k += 1
997
+ continue
998
+ j = k
999
+ while j < n and cls[j] == "N":
1000
+ j += 1
1001
+ if k > 0 and j < n and cls[k - 1] == "R" and cls[j] == "R":
1002
+ for q in range(k, j):
1003
+ out[q] = "R"
1004
+ else:
1005
+ for q in range(k, j):
1006
+ out[q] = "L"
1007
+ k = j
1008
+ return out
1009
+
1010
+
1011
+ def _rtl_text(text: str) -> str:
1012
+ """Logical order of a visually ordered right to left word. Digit runs
1013
+ keep their order, combining marks stay behind their letter and paired
1014
+ brackets are mirrored."""
1015
+ clusters: List[str] = []
1016
+ for ch in text:
1017
+ if clusters and unicodedata.category(ch) == "Mn":
1018
+ clusters[-1] += ch
1019
+ elif (clusters and unicodedata.bidirectional(ch) in ("EN", "AN")
1020
+ and unicodedata.bidirectional(clusters[-1][-1]) in ("EN", "AN")):
1021
+ clusters[-1] += ch
1022
+ else:
1023
+ clusters.append(ch)
1024
+ return "".join(clusters[::-1]).translate(_MIRROR)
1025
+
1026
+
1027
+
1028
+ def _make_line(words: List[_Word], idx: int) -> Line:
1029
+ first = words[0]
1030
+ cc, ss = first.c, first.s
1031
+ rows = []
1032
+ for w in words:
1033
+ us = w.ox * cc + w.oy * ss
1034
+ ue = w.ex * cc + w.ey * ss
1035
+ if ue < us:
1036
+ us, ue = ue, us
1037
+ v = -w.ox * ss + w.oy * cc
1038
+ rows.append((us, ue, v))
1039
+ # weights n * size; ties go to the earlier word of the line
1040
+ v_dom = _dominant_baseline([(rows[k][2], words[k].n * words[k].fs - 1e-6 * k)
1041
+ for k in range(len(words))])
1042
+ size = _heavy([(w.fs, float(w.n)) for w in words])
1043
+ # dominant extent: words standing on the dominant baseline
1044
+ dom_up = dom_dn = 0.0
1045
+ for k, w in enumerate(words):
1046
+ if abs(rows[k][2] - v_dom) <= _BASELINE_TOL_PT:
1047
+ dom_up = max(dom_up, w.up)
1048
+ dom_dn = max(dom_dn, w.dn)
1049
+ dom_top = v_dom - dom_up
1050
+ dom_bot = v_dom + dom_dn
1051
+
1052
+ kinds = [] # +1 superscript, -1 subscript, 0 plain
1053
+ for k, w in enumerate(words):
1054
+ v = rows[k][2]
1055
+ kind = 0
1056
+ if w.fs < _SUPERSCRIPT_SIZE * size:
1057
+ # A raised number usually pokes above the cap height of the text it
1058
+ # follows, so its top may rise above the dominant extent by a
1059
+ # fraction of the line size (a symbol far above is not a script).
1060
+ if v < v_dom - _BASELINE_TOL_PT and v - w.up >= dom_top - _SCRIPT_REACH * size:
1061
+ kind = 1
1062
+ elif v > v_dom + _BASELINE_TOL_PT and v + w.dn <= dom_bot + _BASELINE_TOL_PT:
1063
+ kind = -1
1064
+ kinds.append(kind)
1065
+
1066
+ # flags[k]: a space separates word k-1 and word k
1067
+ flags = [False] * len(words)
1068
+ for k in range(1, len(words)):
1069
+ space = words[k - 1].sp
1070
+ if not space and (kinds[k] == 1) != (kinds[k - 1] == 1):
1071
+ # "Name 1, Other": no space between a raised mark and closing punctuation
1072
+ space = not (kinds[k - 1] == 1 and words[k].chars[0] in _CLOSERS)
1073
+ flags[k] = space
1074
+ texts = [w.text for w in words]
1075
+ cls = _rtl_classes(texts)
1076
+ if "R" in cls:
1077
+ texts = [_rtl_text(t) if c == "R" else t for t, c in zip(texts, cls)]
1078
+ parts: List[str] = []
1079
+ k = 0
1080
+ while k < len(words):
1081
+ if k and flags[k]:
1082
+ parts.append(" ")
1083
+ if cls[k] == "R":
1084
+ j = k
1085
+ while j + 1 < len(words) and cls[j + 1] == "R":
1086
+ j += 1
1087
+ # the stream is in visual order: a run of right to left words reads
1088
+ # from its right end
1089
+ for q in range(j, k - 1, -1):
1090
+ parts.append(texts[q])
1091
+ if q > k and flags[q]:
1092
+ parts.append(" ")
1093
+ k = j + 1
1094
+ else:
1095
+ parts.append(texts[k])
1096
+ k += 1
1097
+
1098
+ ln = Line()
1099
+ ln.text = "".join(parts).strip()
1100
+ ln.x0 = min(w.bx0 for w in words)
1101
+ ln.y0 = min(w.by0 for w in words)
1102
+ ln.x1 = max(w.bx1 for w in words)
1103
+ ln.y1 = max(w.by1 for w in words)
1104
+ ln.size = size
1105
+ ln.nchar = sum(w.n for w in words)
1106
+ ln.nbold = sum(w.nb for w in words)
1107
+ ln.bold = ln.nbold * 2 >= ln.nchar and ln.nbold > 0
1108
+ ln.th = first.th
1109
+ ln.c = cc
1110
+ ln.s = ss
1111
+ ln.v = v_dom
1112
+ ln.us = min(r[0] for r in rows)
1113
+ ln.ue = max(r[1] for r in rows)
1114
+ ln.vt = min(rows[k][2] - words[k].up for k in range(len(words)))
1115
+ ln.vb = max(rows[k][2] + words[k].dn for k in range(len(words)))
1116
+ ln.up = v_dom - ln.vt
1117
+ ln.dn = ln.vb - v_dom
1118
+ ln.px = ln.us * cc - v_dom * ss
1119
+ ln.py = ln.us * ss + v_dom * cc
1120
+ ln.idx = idx
1121
+ ln.nwords = len(words)
1122
+ ln.maxsize = max(w.fs for w in words)
1123
+ out_words = []
1124
+ for w in words:
1125
+ ow = Word()
1126
+ ow.text = texts[len(out_words)]
1127
+ ow.x0, ow.y0, ow.x1, ow.y1 = w.bx0, w.by0, w.bx1, w.by1
1128
+ ow.size = w.fs
1129
+ ow.bold = w.nb * 2 >= w.n and w.nb > 0
1130
+ out_words.append(ow)
1131
+ ln.words = out_words
1132
+ return ln
1133
+
1134
+
1135
+ def _build_lines(words: List[_Word]) -> List[Line]:
1136
+ lines: List[Line] = []
1137
+ cur: List[_Word] = []
1138
+ cc = ss = 0.0
1139
+ run_max = 0.0
1140
+ last_us = last_ue = last_v = 0.0
1141
+ for w in words:
1142
+ if cur:
1143
+ if w.th != cur[0].th and not _ang_close(w.th, cur[0].th):
1144
+ ok = False
1145
+ else:
1146
+ us = w.ox * cc + w.oy * ss
1147
+ ue = w.ex * cc + w.ey * ss
1148
+ v = -w.ox * ss + w.oy * cc
1149
+ if ue < us:
1150
+ us, ue = ue, us
1151
+ dv = v - last_v
1152
+ big = run_max if run_max > w.fs else w.fs
1153
+ if abs(dv) > _ROW_FRAC * big:
1154
+ ok = False
1155
+ elif v - w.up > last_v:
1156
+ ok = False # entirely on a later line
1157
+ elif us < last_us:
1158
+ ok = False # reading went backward
1159
+ elif us < last_ue - _STACK_OVERLAP * run_max and abs(dv) > _ROW_FRAC * run_max:
1160
+ ok = False # stacked material
1161
+ elif us - last_ue > _FAR_FRAC * run_max:
1162
+ ok = False
1163
+ else:
1164
+ ok = True
1165
+ if not ok:
1166
+ lines.append(_make_line(cur, len(lines)))
1167
+ cur = []
1168
+ if not cur:
1169
+ cc, ss = w.c, w.s
1170
+ us = w.ox * cc + w.oy * ss
1171
+ ue = w.ex * cc + w.ey * ss
1172
+ if ue < us:
1173
+ us, ue = ue, us
1174
+ v = -w.ox * ss + w.oy * cc
1175
+ run_max = w.fs
1176
+ else:
1177
+ if w.fs > run_max:
1178
+ run_max = w.fs
1179
+ cur.append(w)
1180
+ last_us, last_ue, last_v = us, ue, v
1181
+ if cur:
1182
+ lines.append(_make_line(cur, len(lines)))
1183
+ return lines
1184
+
1185
+
1186
+ # ---------------------------------------------------------------------------
1187
+ # Interleaved column streams
1188
+ # ---------------------------------------------------------------------------
1189
+ def _upright(ln: Line) -> bool:
1190
+ return ln.th == 0.0
1191
+
1192
+
1193
+ def _lane_assignment(lines: List[Line], page_w: float, info: Optional[dict]) -> Dict[int, Tuple[int, int]]:
1194
+ """Map line index -> (region, lane) for lines inside interleaved regions."""
1195
+ cand = [ln for ln in lines if _upright(ln) and ln.text]
1196
+ if len(cand) < 2 * _MIN_LANE_LINES:
1197
+ return {}
1198
+ wide_cut = _WIDE_LINE_FRAC * page_w if page_w > 0 else float("inf")
1199
+ barrier_y: List[float] = []
1200
+ narrow: List[Line] = []
1201
+ for ln in cand:
1202
+ if ln.x1 - ln.x0 > wide_cut:
1203
+ barrier_y.append((ln.y0 + ln.y1) / 2.0)
1204
+ else:
1205
+ narrow.append(ln)
1206
+ barrier_y.sort()
1207
+ regions: Dict[int, List[Line]] = {}
1208
+ for ln in narrow:
1209
+ regions.setdefault(bisect_right(barrier_y, (ln.y0 + ln.y1) / 2.0), []).append(ln)
1210
+
1211
+ result: Dict[int, Tuple[int, int]] = {}
1212
+ flagged = 0
1213
+ for rid, rl in regions.items():
1214
+ if len(rl) < 2 * _MIN_LANE_LINES:
1215
+ continue
1216
+ body = _heavy([(ln.size, float(ln.nchar)) for ln in rl])
1217
+ # lanes by horizontal overlap
1218
+ lanes: List[list] = [] # [lo, hi, [lines]]
1219
+ for ln in sorted(rl, key=lambda q: (q.x0, q.idx)):
1220
+ if lanes:
1221
+ lane = lanes[-1]
1222
+ overlap = min(lane[1], ln.x1) - max(lane[0], ln.x0)
1223
+ shorter = min(ln.x1 - ln.x0, lane[1] - lane[0])
1224
+ if overlap >= _LANE_OVERLAP * shorter and overlap > 0:
1225
+ lane[1] = max(lane[1], ln.x1)
1226
+ lane[2].append(ln)
1227
+ continue
1228
+ lanes.append([ln.x0, ln.x1, [ln]])
1229
+ merged: List[list] = []
1230
+ for lane in lanes:
1231
+ if merged and lane[0] - merged[-1][1] < body:
1232
+ merged[-1][1] = max(merged[-1][1], lane[1])
1233
+ merged[-1][2].extend(lane[2])
1234
+ else:
1235
+ merged.append(lane)
1236
+ lanes = merged
1237
+ big = [lane for lane in lanes if len(lane[2]) >= _MIN_LANE_LINES]
1238
+ if len(big) < 2:
1239
+ continue
1240
+ lane_of: Dict[int, int] = {}
1241
+ for li, lane in enumerate(lanes):
1242
+ for ln in lane[2]:
1243
+ lane_of[ln.idx] = li
1244
+ seq = sorted(rl, key=lambda q: q.idx)
1245
+ runs = 0
1246
+ prev_lane = None
1247
+ for ln in seq:
1248
+ if lane_of[ln.idx] != prev_lane:
1249
+ runs += 1
1250
+ prev_lane = lane_of[ln.idx]
1251
+ if len(seq) / runs >= _MAX_MEAN_RUN:
1252
+ continue
1253
+ short = sum(1 for ln in rl if ln.x1 - ln.x0 < _SHORT_LINE_L * body)
1254
+ if short * 2 > len(rl):
1255
+ continue
1256
+ good = True
1257
+ for lane in big:
1258
+ ls = sorted(lane[2], key=lambda q: q.idx)
1259
+ ok = tot = 0
1260
+ for a, b in zip(ls, ls[1:]):
1261
+ tot += 1
1262
+ step = b.v - a.v
1263
+ if (0.0 < step < _LEADING * a.size
1264
+ and abs(a.size - b.size) < _SIZE_DIFF * max(a.size, b.size)):
1265
+ ok += 1
1266
+ if tot == 0 or ok < _STEP_OK_FRAC * tot:
1267
+ good = False
1268
+ break
1269
+ if not good:
1270
+ continue
1271
+ flagged += 1
1272
+ for ln in rl:
1273
+ result[ln.idx] = (rid, lane_of[ln.idx])
1274
+ if info is not None:
1275
+ info["interleaved_regions"] = flagged
1276
+ return result
1277
+
1278
+
1279
+ # ---------------------------------------------------------------------------
1280
+ # Lines to blocks
1281
+ # ---------------------------------------------------------------------------
1282
+ def _joins(prev: Line, ln: Line, open_lines: Optional[List[Line]] = None) -> bool:
1283
+ if ln.th != prev.th and not _ang_close(ln.th, prev.th):
1284
+ return False
1285
+ cc, ss = prev.c, prev.s
1286
+ v = -ln.px * ss + ln.py * cc
1287
+ if v + ln.dn < prev.v - prev.up: # bottom above the previous top
1288
+ return False
1289
+ if abs(ln.maxsize - prev.maxsize) >= _SIZE_DIFF * max(ln.maxsize, prev.maxsize):
1290
+ return False
1291
+ if v - prev.v >= _LEADING * prev.size:
1292
+ # items of one bullet list are one block even when the list is spaced out
1293
+ if not (open_lines and v - prev.v < _BULLET_LEADING * prev.size
1294
+ and _BULLET.match(ln.text) and _BULLET.match(open_lines[0].text)):
1295
+ return False
1296
+ if (abs(v - prev.v) < _ROW_FRAC * prev.size and _wholly_bold(prev) and _wholly_bold(ln)
1297
+ and (ln.us - prev.ue > _ROW_SPLIT_GAP * prev.size
1298
+ or prev.us - ln.ue > _ROW_SPLIT_GAP * prev.size)):
1299
+ return False # two headings of different columns on one row
1300
+ return True
1301
+
1302
+
1303
+ def _wholly_bold(ln: Line) -> bool:
1304
+ return ln.nchar > 0 and ln.nbold >= _HEADING_BOLD * ln.nchar
1305
+
1306
+
1307
+ def _heading_ends(open_lines: List[Line], ln: Line) -> bool:
1308
+ """True when the open block is a heading (a few wholly bold lines) and the
1309
+ next line is regular text. A bold tail after body text never splits."""
1310
+ if len(open_lines) > _HEADING_MAX_LINES:
1311
+ return False
1312
+ for q in open_lines:
1313
+ if q.nchar <= 0 or q.nbold < _HEADING_BOLD * q.nchar:
1314
+ return False
1315
+ if ln.nbold * 2 >= ln.nchar:
1316
+ return False
1317
+ if _CONTACT.search(ln.text):
1318
+ return False # a name above its e-mail or ORCID is not a heading
1319
+ # a lone mark ("*", "1") under a bold word belongs to it, not to a paragraph
1320
+ return sum(1 for ch in ln.text if ch.isalnum()) >= _HEADING_NEXT_ALNUM
1321
+
1322
+
1323
+ def _make_block(lines: List[Line]) -> Block:
1324
+ b = Block()
1325
+ b.lines = lines
1326
+ b.x0 = min(ln.x0 for ln in lines)
1327
+ b.y0 = min(ln.y0 for ln in lines)
1328
+ b.x1 = max(ln.x1 for ln in lines)
1329
+ b.y1 = max(ln.y1 for ln in lines)
1330
+ # sizes of one font differ by float noise (30.000000959 vs 30.00000096):
1331
+ # round so that equality tests on the block size are stable
1332
+ b.size = _heavy([(ln.size, float(ln.nchar)) for ln in lines])
1333
+ nch = sum(ln.nchar for ln in lines)
1334
+ nb = sum(ln.nbold for ln in lines)
1335
+ b.bold = nb * 2 >= nch and nb > 0
1336
+ b.first_line_height = max(lines[0].up + lines[0].dn, 1e-6)
1337
+ b.direction = lines[0].th
1338
+ b.seq = lines[0].idx
1339
+ return b
1340
+
1341
+
1342
+ def _build_blocks(lines: List[Line], lane_of: Dict[int, Tuple[int, int]],
1343
+ split_headings: bool = True) -> List[Block]:
1344
+ done: List[Block] = []
1345
+ seq_open: List[Line] = []
1346
+ lane_open: Dict[Tuple[int, int], List[Line]] = {}
1347
+
1348
+ # The first line of the page stands alone when the next item starts clearly
1349
+ # to the right of its end (a title followed by another region).
1350
+ first_alone = False
1351
+ if len(lines) > 1 and lines[0].idx not in lane_of and lines[1].idx not in lane_of:
1352
+ a, b = lines[0], lines[1]
1353
+ if b.th == a.th or _ang_close(b.th, a.th):
1354
+ if b.px * a.c + b.py * a.s - a.ue > _TITLE_JUMP * a.size:
1355
+ first_alone = True
1356
+
1357
+ def flush_lanes():
1358
+ for key in sorted(lane_open, key=lambda k: lane_open[k][0].idx):
1359
+ done.append(_make_block(lane_open[key]))
1360
+ lane_open.clear()
1361
+
1362
+ for i, ln in enumerate(lines):
1363
+ lane = lane_of.get(ln.idx)
1364
+ if lane is not None:
1365
+ if seq_open:
1366
+ done.append(_make_block(seq_open))
1367
+ seq_open = []
1368
+ cur = lane_open.get(lane)
1369
+ if (cur is not None and _joins(cur[-1], ln, cur)
1370
+ and not (split_headings and _heading_ends(cur, ln))):
1371
+ cur.append(ln)
1372
+ else:
1373
+ if cur is not None:
1374
+ done.append(_make_block(cur))
1375
+ lane_open[lane] = [ln]
1376
+ continue
1377
+ if lane_open:
1378
+ flush_lanes()
1379
+ if (seq_open and not (first_alone and i == 1) and _joins(seq_open[-1], ln, seq_open)
1380
+ and not (split_headings and _heading_ends(seq_open, ln))):
1381
+ seq_open.append(ln)
1382
+ continue
1383
+ if seq_open:
1384
+ done.append(_make_block(seq_open))
1385
+ seq_open = [ln]
1386
+ if seq_open:
1387
+ done.append(_make_block(seq_open))
1388
+ flush_lanes()
1389
+ return done
1390
+
1391
+
1392
+ # ---------------------------------------------------------------------------
1393
+ # Block order
1394
+ # ---------------------------------------------------------------------------
1395
+ def _order_blocks(blocks: List[Block]) -> List[Block]:
1396
+ """Top down, then column aware band rule (see module docstring)."""
1397
+ n = len(blocks)
1398
+ if n < 2:
1399
+ return list(blocks)
1400
+ srt = sorted(blocks, key=lambda b: (b.y0, b.seq))
1401
+ # tops that agree within a small tolerance are equal: stream order decides
1402
+ grouped: List[Block] = []
1403
+ start = 0
1404
+ for k in range(1, n + 1):
1405
+ if k == n or srt[k].y0 - srt[k - 1].y0 > max(0.5, 0.1 * srt[k - 1].first_line_height):
1406
+ grouped.extend(sorted(srt[start:k], key=lambda b: b.seq))
1407
+ start = k
1408
+ srt = grouped
1409
+
1410
+ top = [b.y0 for b in srt]
1411
+ bot = [b.y1 for b in srt]
1412
+ tol = [b.first_line_height for b in srt]
1413
+
1414
+ # related to an earlier block: running maximum of (bottom + tolerance), or
1415
+ # the nearest earlier top lies within this block's tolerance above it
1416
+ prev_rel = [False] * n
1417
+ run_max = float("-inf")
1418
+ for k in range(n):
1419
+ if k:
1420
+ prev_rel[k] = top[k] <= run_max or top[k] - top[k - 1] <= tol[k]
1421
+ run_max = max(run_max, bot[k] + tol[k])
1422
+ # related to a later block: next top inside this extent, or some later
1423
+ # block has this top inside its own widened extent
1424
+ next_rel = [False] * n
1425
+ suffix_min = float("inf")
1426
+ for k in range(n - 2, -1, -1):
1427
+ suffix_min = min(suffix_min, top[k + 1] - tol[k + 1])
1428
+ next_rel[k] = top[k + 1] <= bot[k] + tol[k] or suffix_min <= top[k]
1429
+ banded = [prev_rel[k] or next_rel[k] for k in range(n)]
1430
+
1431
+ out: List[Block] = []
1432
+ k = 0
1433
+ while k < n:
1434
+ if not banded[k]:
1435
+ out.append(srt[k])
1436
+ k += 1
1437
+ continue
1438
+ j = k
1439
+ while j < n and banded[j]:
1440
+ j += 1
1441
+ placed: List[Block] = []
1442
+ floor_pos = 1 if k == 0 else 0
1443
+ band = srt[k:j]
1444
+ page_span = max(q.x1 for q in srt) - min(q.x0 for q in srt)
1445
+ span_memo: Dict[int, bool] = {}
1446
+ for t in range(k, j):
1447
+ b = srt[t]
1448
+ pos = len(placed)
1449
+ steps = 0
1450
+ while pos > floor_pos and steps < _HOP_CAP and placed[pos - 1].x0 > b.x1:
1451
+ p = placed[pos - 1]
1452
+ if p.y1 <= b.y0:
1453
+ # a banner wholly above b is read first, whatever its left edge
1454
+ sp = span_memo.get(id(p))
1455
+ if sp is None:
1456
+ sp = span_memo[id(p)] = _spans_columns(p, band, page_span)
1457
+ if sp:
1458
+ break
1459
+ pos -= 1
1460
+ steps += 1
1461
+ placed.insert(pos, b)
1462
+ out.extend(placed)
1463
+ k = j
1464
+ return _bind_side_labels(out)
1465
+
1466
+
1467
+ def _spans_columns(p: Block, band: List[Block], page_span: float) -> bool:
1468
+ """True when ``p`` is a wide block above and across two or more separate columns,
1469
+ with no column of the band starting above it to either side."""
1470
+ if p.x1 - p.x0 < _BANNER_FRAC * page_span:
1471
+ return False
1472
+ below = []
1473
+ for q in band:
1474
+ if q is p:
1475
+ continue
1476
+ if q.y0 < p.y0 - 1e-6 and (q.x1 <= p.x0 or q.x0 >= p.x1):
1477
+ return False # a column already started beside it: not a banner
1478
+ if q.y0 < p.y1 - 1e-6:
1479
+ continue
1480
+ ov = min(p.x1, q.x1) - max(p.x0, q.x0)
1481
+ if ov > 0 and ov >= 0.5 * (q.x1 - q.x0):
1482
+ below.append(q)
1483
+ count = 0
1484
+ last = float("-inf")
1485
+ for q in sorted(below, key=lambda q: q.x0):
1486
+ if q.x0 >= last:
1487
+ count += 1
1488
+ last = q.x1
1489
+ if count >= 2:
1490
+ return True
1491
+ return False
1492
+
1493
+
1494
+ def _bind_side_labels(blocks: List[Block]) -> List[Block]:
1495
+ """Put a heading that stands left of the text it names right before that text.
1496
+
1497
+ A margin label ("Cells", "Methods" printed beside its row) has no text of its
1498
+ own below it; the block to its right that spans its height is what it
1499
+ heads. A heading with its paragraph underneath is never touched.
1500
+ """
1501
+ n = len(blocks)
1502
+ if n < 2:
1503
+ return blocks
1504
+ moves: List[Tuple[Block, Block]] = []
1505
+ for b in blocks:
1506
+ if b.direction != 0.0 or len(b.lines) > 2:
1507
+ continue
1508
+ bh = b.y1 - b.y0
1509
+ tol = 0.5 * b.first_line_height
1510
+ best = None
1511
+ for r in blocks:
1512
+ if r is b or r.direction != 0.0 or r.x0 < b.x1:
1513
+ continue
1514
+ gap = r.x0 - b.x1
1515
+ if gap > _SIDE_GAP * b.size:
1516
+ continue
1517
+ if not (r.y0 - tol <= b.y0 and b.y1 <= r.y1 + tol) or r.y1 - r.y0 < bh:
1518
+ continue
1519
+ if not (b.bold or b.size > r.size * 1.1) or (r.x1 - r.x0) <= (b.x1 - b.x0):
1520
+ continue
1521
+ if best is None or gap < best.x0 - b.x1:
1522
+ best = r
1523
+ if best is None:
1524
+ continue
1525
+ own = False
1526
+ for q in blocks:
1527
+ if q is b or q.y0 < b.y1 - 1e-6 or q.y0 - b.y1 > _SIDE_BELOW * bh:
1528
+ continue
1529
+ ov = min(b.x1, q.x1) - max(b.x0, q.x0)
1530
+ if ov > 0 and ov >= 0.3 * min(b.x1 - b.x0, q.x1 - q.x0):
1531
+ own = True
1532
+ break
1533
+ if not own:
1534
+ moves.append((b, best))
1535
+ if not moves:
1536
+ return blocks
1537
+ movers = {id(b) for b, _ in moves}
1538
+ moves = [(b, r) for b, r in moves if id(r) not in movers]
1539
+ movers = {id(b) for b, _ in moves}
1540
+ target: Dict[int, List[Block]] = {}
1541
+ for b, r in moves:
1542
+ target.setdefault(id(r), []).append(b)
1543
+ out: List[Block] = []
1544
+ for blk in blocks:
1545
+ if id(blk) in movers:
1546
+ continue
1547
+ out.extend(target.get(id(blk), ()))
1548
+ out.append(blk)
1549
+ return out
1550
+
1551
+
1552
+ # ---------------------------------------------------------------------------
1553
+ # Entry point
1554
+ # ---------------------------------------------------------------------------
1555
+ def ordered_blocks(page, chars: Optional[Sequence[dict]] = None, *,
1556
+ repair_interleave: bool = True,
1557
+ split_headings: bool = True,
1558
+ info: Optional[dict] = None) -> List[Block]:
1559
+ """Blocks of one pdfplumber page in reading order.
1560
+
1561
+ ``chars`` defaults to ``page.chars`` (content-stream order). Coordinates
1562
+ of the result are relative to the page box origin. ``info`` receives
1563
+ counters (glyphs, words, lines, blocks, interleaved_regions). With
1564
+ ``split_headings`` a short wholly bold block is closed before regular text
1565
+ of the same size that follows it; ``False`` gives the plain stream rules.
1566
+ """
1567
+ if chars is None:
1568
+ chars = page.chars
1569
+ frame = _page_frame(page)
1570
+ items = _prepare(page, chars, frame, info)
1571
+ items = _drop_overprints(items)
1572
+ items = _merge_accents(_dot_pairs(items))
1573
+ words = _build_words(items)
1574
+ lines = _build_lines(words)
1575
+ lines = [ln for ln in lines if ln.text]
1576
+ for i, ln in enumerate(lines):
1577
+ ln.idx = i
1578
+ lane_of: Dict[int, Tuple[int, int]] = {}
1579
+ if repair_interleave and lines:
1580
+ lane_of = _lane_assignment(lines, frame[2], info)
1581
+ blocks = _build_blocks(lines, lane_of, split_headings)
1582
+ blocks = _order_blocks(blocks)
1583
+ if info is not None:
1584
+ info.setdefault("interleaved_regions", 0)
1585
+ info["glyphs"] = sum(1 for g in items if isinstance(g, _Glyph))
1586
+ info["words"] = len(words)
1587
+ info["lines"] = len(lines)
1588
+ info["blocks"] = len(blocks)
1589
+ return blocks
src/poster_sentry/p2j/text.py ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """First-page text extraction, vendored from poster2json 0.10.5.
2
+
3
+ This module is a verbatim copy of the pdfplumber text path of poster2json
4
+ (``poster2json.extract.extract_text_with_pdfplumber`` and the helpers it calls,
5
+ with its "alto" layout engine in ``layout_streams``), by the FAIR Data
6
+ Innovations Hub, MIT license: https://github.com/fairdataihub/poster2json
7
+ (commit dcb856f). It is vendored so that PosterSentry keeps its small,
8
+ permissively licensed dependency set; poster2json itself depends on torch,
9
+ transformers, and PyMuPDF. Changes from upstream: imports are relative,
10
+ logging goes to the module logger instead of stdout, environment overrides
11
+ (POSTER2JSON_LAYOUT, POSTER2JSON_CAPTIONS) are not read, caption detection
12
+ is not included, and ``max_pages`` limits extraction to the first pages.
13
+ """
14
+
15
+ import logging
16
+ import time
17
+ import math
18
+ import re
19
+ import unicodedata
20
+ from typing import Optional, Tuple
21
+
22
+ import numpy as np
23
+ import pdfplumber
24
+
25
+ _logger = logging.getLogger(__name__)
26
+
27
+
28
+ _TRUTHY_ENV = {"1", "true", "yes", "on"}
29
+
30
+
31
+ CAPTION_ENGINE = False
32
+
33
+
34
+ CAPTION_RAW_MODE = "marker"
35
+
36
+
37
+ _SECTION_KEYWORDS = frozenset({
38
+ "abstract", "introduction", "background", "objective", "objectives",
39
+ "aim", "aims", "hypothesis", "methods", "methodology",
40
+ "materials and methods", "results", "results and discussion",
41
+ "discussion", "conclusion", "conclusions", "summary",
42
+ "references", "reference", "bibliography",
43
+ "acknowledgements", "acknowledgments", "acknowledgement",
44
+ "funding", "limitations", "future work", "future directions",
45
+ "contact", "contact information",
46
+ })
47
+
48
+
49
+ _INLINE_LABELS = (
50
+ "REFERENCES", "REFERENCE", "BIBLIOGRAPHY", "ABBREVIATIONS",
51
+ "DISCLOSURES", "DISCLOSURE", "ACKNOWLEDGEMENTS", "ACKNOWLEDGMENTS",
52
+ "FUNDING", "CONFLICTS OF INTEREST", "CONFLICT OF INTEREST",
53
+ "COMPETING INTERESTS", "CORRESPONDING AUTHOR", "CONTACT",
54
+ "CONCLUSIONS", "CONCLUSION",
55
+ )
56
+
57
+
58
+ _INLINE_LABEL_RE = re.compile(
59
+ r"(?:(?<=[\s.;)])|^)(" + "|".join(_INLINE_LABELS) + r")\s*:\s+"
60
+ )
61
+
62
+
63
+ _INLINE_DASH_HEAD_RE = re.compile(
64
+ r"(?:(?<=[.;])\s+|^)([A-Z][A-Z]{2,})\s*[—–]\s+(?=[A-Z])"
65
+ )
66
+
67
+
68
+ def log(msg: str):
69
+ """Debug logging (poster2json prints a timestamped line)."""
70
+ _logger.debug(msg)
71
+
72
+
73
+ def _parse_font_style(fontname: str) -> dict:
74
+ """Parse bold/italic from a pdfplumber fontname string.
75
+
76
+ Font names follow the pattern 'SUBSET+FamilyName-Style' where style
77
+ contains 'Bold', 'Italic', 'BoldItalic', etc.
78
+ """
79
+ lower = fontname.lower()
80
+ suffix = lower.rsplit("-", 1)[-1] if "-" in lower else ""
81
+ return {
82
+ "bold": ("bold" in lower or "black" in lower or "heavy" in lower
83
+ or "bd" in suffix or "demi" in suffix),
84
+ "italic": ("italic" in lower or "oblique" in lower or "it" in suffix),
85
+ }
86
+
87
+
88
+ def _filter_phantom_spaces(chars: list) -> list:
89
+ """Remove space characters fully contained within a non-space character.
90
+
91
+ Some PDFs embed invisible space glyphs on top of real characters, causing
92
+ pdfplumber's extract_words to split words at those phantom boundaries
93
+ (e.g. "For" → "F or"). A phantom space is one whose entire horizontal
94
+ extent [x0, x1] falls within a non-space character's [x0, x1] on the
95
+ same line. Legitimate word-separating spaces extend beyond the adjacent
96
+ character's bounds and are preserved.
97
+ """
98
+ non_space = [(c["x0"], c["x1"], c["top"]) for c in chars if c["text"].strip()]
99
+ if not non_space:
100
+ return chars
101
+
102
+ from bisect import bisect_right
103
+
104
+ ns_by_row = {}
105
+ for x0, x1, top in non_space:
106
+ row = round(top)
107
+ ns_by_row.setdefault(row, []).append((x0, x1))
108
+ for row in ns_by_row:
109
+ ns_by_row[row].sort()
110
+
111
+ filtered = []
112
+ for c in chars:
113
+ if not c["text"].strip():
114
+ row = round(c["top"])
115
+ is_phantom = False
116
+ for r in (row - 1, row, row + 1):
117
+ intervals = ns_by_row.get(r)
118
+ if not intervals:
119
+ continue
120
+ idx = bisect_right(intervals, (c["x0"], float("inf"))) - 1
121
+ if idx >= 0 and intervals[idx][0] <= c["x0"] + 1 and c["x1"] <= intervals[idx][1] + 1:
122
+ is_phantom = True
123
+ break
124
+ if is_phantom:
125
+ continue
126
+ filtered.append(c)
127
+ return filtered
128
+
129
+
130
+ def _annotate_words_with_fonts(words: list, chars: list) -> None:
131
+ """Add fontname to each word from overlapping raw characters.
132
+
133
+ pdfplumber's extract_words groups chars by extra_attrs, which means
134
+ including fontname would break words at font-subset boundaries (e.g.
135
+ ligature ff in a different subset splitting "different" → "di|ff|erent").
136
+ We extract with extra_attrs=["size"] only, then look up each word's
137
+ dominant fontname from the raw chars.
138
+ """
139
+ from bisect import bisect_left, bisect_right
140
+
141
+ non_space = [c for c in chars if c["text"].strip()]
142
+ if not non_space:
143
+ return
144
+ non_space.sort(key=lambda c: (round(c["top"]), c["x0"]))
145
+ tops = [round(c["top"]) for c in non_space]
146
+
147
+ for w in words:
148
+ w_top = round(w["top"])
149
+ lo = bisect_left(tops, w_top - 2)
150
+ hi = bisect_right(tops, w_top + 2)
151
+ matching = [
152
+ c for c in non_space[lo:hi]
153
+ if c["x0"] >= w["x0"] - 1 and c["x1"] <= w["x1"] + 1
154
+ ]
155
+ if matching:
156
+ fonts = [c["fontname"] for c in matching if c.get("fontname")]
157
+ w["fontname"] = max(set(fonts), key=fonts.count) if fonts else ""
158
+ else:
159
+ w["fontname"] = ""
160
+
161
+
162
+ def _line_is_bold(line: list) -> bool:
163
+ """Check if a line's dominant font is bold."""
164
+ styles = [_parse_font_style(w.get("fontname", "")) for w in line]
165
+ bold_count = sum(1 for s in styles if s["bold"])
166
+ return bold_count > len(styles) / 2 if styles else False
167
+
168
+
169
+ def _line_dominant_size(line: list) -> float:
170
+ """Get the most common font size in a line."""
171
+ sizes = [w["size"] for w in line if w.get("size", 0) > 0]
172
+ if not sizes:
173
+ return 0
174
+ return max(set(sizes), key=sizes.count)
175
+
176
+
177
+ def _lines_to_blocks(lines: list, line_height_mult: float = 1.5,
178
+ leaf_ids: Optional[list] = None,
179
+ hyphen_join: bool = False,
180
+ orders: Optional[list] = None) -> list:
181
+ """Group word lines (in reading order) into blocks.
182
+
183
+ A new block starts when:
184
+ - The vertical gap exceeds line_height_mult * median line height, OR
185
+ - The font style changes (bold to non-bold or vice versa), OR
186
+ - The font size jumps significantly (> 1.3x ratio), OR
187
+ - (when leaf_ids is given, one XY-cut column region id per line) the
188
+ line belongs to a different column region than the previous line, or
189
+ starts clearly above the previous line (an upward jump means a column
190
+ or flow change, never a continuation)
191
+
192
+ With hyphen_join, words hyphenated at line ends are repaired when the
193
+ lines of a block are joined.
194
+ """
195
+ if not lines:
196
+ return []
197
+
198
+ line_heights = []
199
+ for line in lines:
200
+ h = max(w["bottom"] for w in line) - min(w["top"] for w in line)
201
+ line_heights.append(max(h, 1.0))
202
+ median_lh = sorted(line_heights)[len(line_heights) // 2]
203
+ gap_threshold = median_lh * line_height_mult
204
+
205
+ vocab = None
206
+ if hyphen_join:
207
+ from .layout_blocks import page_vocab
208
+ vocab = page_vocab([" ".join(w["text"] for w in ln) for ln in lines])
209
+
210
+ block_groups = [[lines[0]]]
211
+ group_region = [leaf_ids[0] if leaf_ids is not None else 0]
212
+ group_order = [orders[0] if orders is not None else 0]
213
+ for i in range(1, len(lines)):
214
+ prev_bottom = max(w["bottom"] for w in lines[i - 1])
215
+ curr_top = min(w["top"] for w in lines[i])
216
+ gap = curr_top - prev_bottom
217
+
218
+ prev_bold = _line_is_bold(lines[i - 1])
219
+ curr_bold = _line_is_bold(lines[i])
220
+ prev_size = _line_dominant_size(lines[i - 1])
221
+ curr_size = _line_dominant_size(lines[i])
222
+ size_ratio = max(curr_size, prev_size) / max(min(curr_size, prev_size), 0.1)
223
+
224
+ style_break = False
225
+ if size_ratio > 1.3:
226
+ style_break = True
227
+ elif prev_bold != curr_bold and gap > 0:
228
+ curr_text = " ".join(w["text"] for w in lines[i])
229
+ prev_text = " ".join(w["text"] for w in lines[i - 1])
230
+ short_line = len(curr_text) <= 120 or len(prev_text) <= 120
231
+ if short_line:
232
+ style_break = True
233
+
234
+ leaf_break = False
235
+ if leaf_ids is not None:
236
+ prev_top = min(w["top"] for w in lines[i - 1])
237
+ prev_h = max(prev_bottom - prev_top, 1.0)
238
+ # Different column region: break, unless the line continues the
239
+ # previous one on the same row (e.g. a bullet or number in its
240
+ # own cell next to its text).
241
+ same_row = (abs(curr_top - prev_top) < 0.5 * prev_h
242
+ and min(w["x0"] for w in lines[i])
243
+ >= max(w["x1"] for w in lines[i - 1]) - 1.0)
244
+ leaf_break = ((leaf_ids[i] != leaf_ids[i - 1] and not same_row)
245
+ or curr_top < prev_top - 0.25 * prev_h)
246
+ if leaf_break and not same_row:
247
+ from .layout_blocks import continues_paragraph
248
+ # a paragraph can run from the bottom of one column into the
249
+ # top of the next; keep that as one block
250
+ if continues_paragraph(" ".join(w["text"] for w in lines[i - 1]),
251
+ " ".join(w["text"] for w in lines[i])):
252
+ leaf_break = False
253
+
254
+ if gap > gap_threshold or style_break or leaf_break:
255
+ block_groups.append([lines[i]])
256
+ group_region.append(leaf_ids[i] if leaf_ids is not None else 0)
257
+ group_order.append(orders[i] if orders is not None else i)
258
+ else:
259
+ block_groups[-1].append(lines[i])
260
+
261
+ blocks = []
262
+ for group, region, order in zip(block_groups, group_region, group_order):
263
+ all_words = [w for line in group for w in line]
264
+ x0 = min(w["x0"] for w in all_words)
265
+ top = min(w["top"] for w in all_words)
266
+ x1 = max(w["x1"] for w in all_words)
267
+ bottom = max(w["bottom"] for w in all_words)
268
+ bw = x1 - x0
269
+ bh = bottom - top
270
+ cx = x0 + bw / 2
271
+
272
+ seen_texts = []
273
+ deduped_lines = []
274
+ for line in group:
275
+ line_top = min(w["top"] for w in line)
276
+ line_words = set(w["text"] for w in line)
277
+ line_text = " ".join(w["text"] for w in line)
278
+
279
+ is_dup = False
280
+ for sv, sw, _ in seen_texts:
281
+ if abs(sv - line_top) < 2:
282
+ if line_words and sw:
283
+ overlap = len(line_words & sw) / max(len(line_words), len(sw))
284
+ if overlap > 0.8:
285
+ is_dup = True
286
+ break
287
+ if not is_dup:
288
+ seen_texts.append((line_top, line_words, line_text))
289
+ deduped_lines.append(line_text)
290
+
291
+ if not deduped_lines:
292
+ continue
293
+
294
+ if hyphen_join:
295
+ from .layout_blocks import join_lines
296
+ block_text = join_lines(deduped_lines, vocab)
297
+ else:
298
+ block_text = " ".join(deduped_lines)
299
+
300
+ fontsizes = [w["size"] for w in all_words if w.get("size", 0) > 0]
301
+ fontnames = [w["fontname"] for w in all_words if w.get("fontname")]
302
+
303
+ dominant_size = max(set(fontsizes), key=fontsizes.count) if fontsizes else 0
304
+ styles = [_parse_font_style(fn) for fn in fontnames]
305
+ bold_count = sum(1 for s in styles if s["bold"])
306
+ is_bold = bold_count > len(styles) / 2 if styles else False
307
+
308
+ blocks.append({
309
+ "hpos": x0,
310
+ "vpos": top,
311
+ "width": bw,
312
+ "height": bh,
313
+ "cx": cx,
314
+ "text": block_text,
315
+ "fontsize": dominant_size,
316
+ "bold": is_bold,
317
+ "region": region,
318
+ "order": order,
319
+ })
320
+
321
+ return blocks
322
+
323
+
324
+ def _chars_to_word_lines(char_lines, words, leaf_ids=None):
325
+ """Map XY-cut char-level lines back to word-level lines.
326
+
327
+ For each char-level line, find the words whose characters
328
+ predominantly fall on that line (by spatial overlap). Legacy path used
329
+ when layout_blocks.FLAGS["decomp"] is off. With leaf_ids (one per char
330
+ line) the result is (word_lines, leaf id per word line); words that no
331
+ line claimed get leaf id -1.
332
+ """
333
+ from bisect import bisect_left, bisect_right
334
+
335
+ word_tops = sorted(set(w["top"] for w in words))
336
+ word_by_pos = {}
337
+ for w in words:
338
+ key = (round(w["top"], 1), round(w["x0"], 1))
339
+ word_by_pos[key] = w
340
+
341
+ assigned = set()
342
+ result = []
343
+ result_leaf = []
344
+ for li, char_line in enumerate(char_lines):
345
+ if not char_line:
346
+ continue
347
+ line_y_min = min(c["top"] for c in char_line)
348
+ line_y_max = max(c["bottom"] for c in char_line)
349
+ line_x_min = min(c["x0"] for c in char_line)
350
+ line_x_max = max(c["x1"] for c in char_line)
351
+
352
+ line_words = []
353
+ for w in words:
354
+ if id(w) in assigned:
355
+ continue
356
+ w_cy = (w["top"] + w["bottom"]) / 2
357
+ w_cx = (w["x0"] + w["x1"]) / 2
358
+ if (line_y_min - 2 <= w_cy <= line_y_max + 2
359
+ and line_x_min - 5 <= w_cx <= line_x_max + 5):
360
+ line_words.append(w)
361
+ assigned.add(id(w))
362
+
363
+ if line_words:
364
+ line_words.sort(key=lambda w: w["x0"])
365
+ result.append(line_words)
366
+ result_leaf.append(leaf_ids[li] if leaf_ids is not None else 0)
367
+
368
+ unassigned = [w for w in words if id(w) not in assigned]
369
+ if unassigned:
370
+ unassigned.sort(key=lambda w: (w["top"], w["x0"]))
371
+ cur = [unassigned[0]]
372
+ for w in unassigned[1:]:
373
+ if abs(w["top"] - cur[0]["top"]) <= 3:
374
+ cur.append(w)
375
+ else:
376
+ result.append(sorted(cur, key=lambda w: w["x0"]))
377
+ result_leaf.append(-1)
378
+ cur = [w]
379
+ if cur:
380
+ result.append(sorted(cur, key=lambda w: w["x0"]))
381
+ result_leaf.append(-1)
382
+
383
+ if leaf_ids is not None:
384
+ return result, result_leaf
385
+ return result
386
+
387
+
388
+ def _split_inline_sections(text: str):
389
+ """Split a run-on block at inline ALL-CAPS section labels and em-dash
390
+ sub-headers. Returns a list of (heading_or_None, body) segments, or None
391
+ if the block contains no inline boundary (the common case)."""
392
+ marks = []
393
+ for m in _INLINE_LABEL_RE.finditer(text):
394
+ marks.append((m.start(), m.end(), m.group(1).title()))
395
+ for m in _INLINE_DASH_HEAD_RE.finditer(text):
396
+ marks.append((m.start(), m.end(), m.group(1).title()))
397
+ if not marks:
398
+ return None
399
+ marks.sort()
400
+ segments = []
401
+ pre = text[:marks[0][0]].strip()
402
+ if pre:
403
+ segments.append((None, pre))
404
+ for i, (_s, end, heading) in enumerate(marks):
405
+ nxt = marks[i + 1][0] if i + 1 < len(marks) else len(text)
406
+ segments.append((heading, text[end:nxt].strip()))
407
+ return segments
408
+
409
+
410
+ def _xy_cut_blocks(page, chars, text_chars, x_tol, page_w, page_h,
411
+ geo: Optional[dict] = None) -> Tuple[list, list]:
412
+ """Blocks and figure-label blocks for one page from the XY-cut tree and
413
+ leaf-aware line builder."""
414
+ from pdfplumber.utils.text import extract_words as _pw_extract_words
415
+ from . import layout_blocks as _lb
416
+ from . import xy_cut as _xy
417
+
418
+ leaf_ids = None
419
+ if _lb.FLAGS["decomp"]:
420
+ # One decomposition: lines and words come from the same chars
421
+ # of each XY-cut leaf, so every word belongs to exactly one line.
422
+ rot_chars = []
423
+ main_chars = chars
424
+ if _lb.FLAGS["rotated"]:
425
+ main_chars, rot_chars = _lb.split_rotated(chars)
426
+ # The XY-cut sees every char (the cut tree is the same with or
427
+ # without rotated labels); rotated chars are pulled out of the
428
+ # leaves afterwards.
429
+ leaves, regions = _xy.chars_to_leaves(
430
+ chars, page_width=page_w, page_height=page_h)
431
+ if rot_chars:
432
+ rot_ids = {id(c) for c in rot_chars}
433
+ kept = [([c for c in lf if id(c) not in rot_ids], rg)
434
+ for lf, rg in zip(leaves, regions)]
435
+ kept = [(lf, rg) for lf, rg in kept if lf]
436
+ leaves = [lf for lf, _ in kept]
437
+ regions = [rg for _, rg in kept]
438
+ if not leaves and not rot_chars:
439
+ return [], []
440
+ word_lines, leaf_ids = _lb.build_word_lines(
441
+ leaves, x_tol, _lb.body_font_size(text_chars), regions=regions,
442
+ spaces=[c for c in main_chars if c.get("text") == " "])
443
+ if rot_chars:
444
+ rlines, rids = _lb.rotated_word_lines(rot_chars, x_tol)
445
+ word_lines = word_lines + rlines
446
+ leaf_ids = leaf_ids + rids
447
+ else:
448
+ words = _pw_extract_words(chars, x_tolerance=x_tol,
449
+ extra_attrs=["size"],
450
+ use_text_flow=True)
451
+ _annotate_words_with_fonts(words, chars)
452
+ if not words:
453
+ return [], []
454
+ reading_lines, line_leaf = _xy.chars_to_leaf_lines(
455
+ chars, page_width=page_w, page_height=page_h)
456
+ if not reading_lines:
457
+ return [], []
458
+ word_lines, leaf_ids = _chars_to_word_lines(
459
+ reading_lines, words, leaf_ids=line_leaf)
460
+ if not word_lines:
461
+ return [], []
462
+
463
+ # Figure/table label text (plot ticks, table cells) is split off
464
+ # into its own blocks so it is not glued into body sentences.
465
+ fig_blocks = []
466
+ want_geo = geo is not None
467
+ masks = None
468
+ if want_geo:
469
+ geo["words"] = [w for ln in word_lines for w in ln]
470
+ if _lb.FLAGS["fig"] or want_geo:
471
+ masks = _lb.build_figure_masks(
472
+ page.images,
473
+ list(page.rects) + list(page.curves) + list(page.lines),
474
+ page_w, page_h, _lb.body_font_size(text_chars))
475
+ if want_geo:
476
+ geo["masks"] = masks
477
+ if _lb.FLAGS["fig"]:
478
+ (body_lines, body_ids, lab_lines, lab_ids,
479
+ body_order, lab_order) = _lb.split_figure_words(
480
+ word_lines, leaf_ids, masks, _lb.body_font_size(text_chars))
481
+ if body_lines and lab_lines:
482
+ word_lines, leaf_ids, line_order = body_lines, body_ids, body_order
483
+ fig_blocks = _lines_to_blocks(
484
+ lab_lines, leaf_ids=lab_ids if _lb.FLAGS["leaf"] else None,
485
+ orders=lab_order)
486
+ for fb in fig_blocks:
487
+ fb["fig"] = True
488
+ else:
489
+ line_order = None
490
+ else:
491
+ line_order = None
492
+
493
+ all_blocks = _lines_to_blocks(
494
+ word_lines,
495
+ leaf_ids=leaf_ids if _lb.FLAGS["leaf"] else None,
496
+ hyphen_join=_lb.FLAGS["hyphen"], orders=line_order)
497
+ return all_blocks, fig_blocks
498
+
499
+
500
+ LAYOUT_ENGINE = "alto"
501
+
502
+
503
+ def _layout_engine() -> str:
504
+ eng = (LAYOUT_ENGINE or "alto").strip().lower()
505
+ return eng if eng in ("blocks", "alto") else "alto"
506
+
507
+
508
+ def _alto_blocks(page, chars, page_w, page_h, geo: Optional[dict] = None) -> list:
509
+ """Blocks for one page from layout_streams, in the dict form _lines_to_blocks makes."""
510
+ from . import layout_blocks as _lb
511
+ from . import layout_streams as _ls
512
+
513
+ info = {}
514
+ ablocks = _ls.ordered_blocks(page, chars=chars, info=info)
515
+ log(f" stream layout glyphs={info.get('glyphs')} lines={info.get('lines')} "
516
+ f"interleaved={info.get('interleaved_regions', 0)} blocks={len(ablocks)}")
517
+ if not ablocks:
518
+ return []
519
+ if geo is not None:
520
+ geo["words"] = [
521
+ {"x0": w.x0, "x1": w.x1, "top": w.y0, "bottom": w.y1,
522
+ "text": w.text, "size": w.size}
523
+ for b in ablocks for ln in b.lines for w in (ln.words or ())]
524
+ vocab = _lb.page_vocab([ln.text for b in ablocks for ln in b.lines])
525
+ blocks = []
526
+ for order, ab in enumerate(ablocks):
527
+ texts = [ln.text for ln in ab.lines if ln.text]
528
+ if not texts:
529
+ continue
530
+ text = _lb.join_lines(texts, vocab)
531
+ blocks.append({
532
+ "hpos": ab.x0,
533
+ "vpos": ab.y0,
534
+ "width": ab.x1 - ab.x0,
535
+ "height": ab.y1 - ab.y0,
536
+ "cx": ab.x0 + (ab.x1 - ab.x0) / 2,
537
+ "text": text,
538
+ "fontsize": ab.size,
539
+ "bold": ab.bold,
540
+ "region": 0,
541
+ "order": order,
542
+ "rotated": bool(ab.direction),
543
+ })
544
+ return blocks
545
+
546
+
547
+ def _alto_masks(page, chars, page_w, page_h, geo: dict) -> None:
548
+ """Figure and table regions of the page for the caption module (alto engine)."""
549
+ from . import layout_blocks as _lb
550
+
551
+ _tc, _xt, _ = _char_stats(chars, tolerant=True)
552
+ try:
553
+ geo["masks"] = _lb.build_figure_masks(
554
+ page.images,
555
+ list(page.rects) + list(page.curves) + list(page.lines),
556
+ page_w, page_h, _lb.body_font_size(_tc))
557
+ except Exception as e: # noqa: BLE001 - regions are optional for captions
558
+ log(f" figure regions unavailable ({type(e).__name__}: {e})")
559
+ geo["masks"] = []
560
+
561
+
562
+ def _char_stats(chars: list, tolerant: bool = False) -> Tuple[list, float, float]:
563
+ """Text chars, x tolerance and median font size of a page's chars.
564
+
565
+ ``tolerant`` (alto engine) ignores chars whose size or box is not a
566
+ finite number instead of raising.
567
+ """
568
+ def _ok(c) -> bool:
569
+ if not c.get("text", "").strip():
570
+ return False
571
+ if not tolerant:
572
+ return True
573
+ try:
574
+ return all(math.isfinite(float(c[k])) for k in ("size",))
575
+ except (KeyError, TypeError, ValueError):
576
+ return False
577
+
578
+ text_chars = [c for c in chars if _ok(c)]
579
+ median_fs = 0.0
580
+ if text_chars:
581
+ median_fs = float(np.median([c["size"] for c in text_chars]))
582
+ x_tol = round(max(1.5, min(median_fs * 0.25, 3.0)), 2)
583
+ space_chars = []
584
+ for c in chars:
585
+ if c.get("text") != " ":
586
+ continue
587
+ try:
588
+ if c["x1"] - c["x0"] > 0:
589
+ space_chars.append(c)
590
+ except (KeyError, TypeError):
591
+ if not tolerant:
592
+ raise
593
+ if space_chars:
594
+ space_w = float(np.median([c["x1"] - c["x0"] for c in space_chars]))
595
+ x_tol = round(min(x_tol, space_w * 0.7), 2)
596
+ else:
597
+ x_tol = 3
598
+ return text_chars, x_tol, median_fs
599
+
600
+
601
+ def _page_blocks(page, chars, text_chars, x_tol, page_w, page_h,
602
+ geo: Optional[dict] = None) -> Tuple[list, list, bool]:
603
+ """Blocks, figure-label blocks and whether the alto engine made them.
604
+
605
+ Any failure of the alto engine (including RecursionError) is logged and
606
+ that page falls back to the default blocks engine.
607
+
608
+ ``geo``, when given, receives ``words`` (page words as dicts with x0, x1,
609
+ top, bottom, text, size) and ``masks`` (figure and table regions) for the
610
+ caption module, whichever engine made the blocks.
611
+ """
612
+ if _layout_engine() == "alto":
613
+ try:
614
+ if geo is not None:
615
+ geo.clear()
616
+ blocks = _alto_blocks(page, chars, page_w, page_h, geo)
617
+ if geo is not None:
618
+ _alto_masks(page, chars, page_w, page_h, geo)
619
+ return blocks, [], True
620
+ except Exception as e: # noqa: BLE001 - includes RecursionError
621
+ log(f" alto layout failed ({type(e).__name__}: {e}); using the blocks engine")
622
+ from . import layout_blocks as _lb
623
+ if _lb.FLAGS["dedupe"]:
624
+ chars = _lb.dedupe_overprinted(chars)
625
+ for _i, _c in enumerate(chars):
626
+ _c["_si"] = _i
627
+ text_chars, x_tol, _ = _char_stats(chars, tolerant=True)
628
+ if not text_chars:
629
+ return [], [], False
630
+ all_blocks, fig_blocks = _xy_cut_blocks(page, chars, text_chars, x_tol, page_w, page_h, geo)
631
+ return all_blocks, fig_blocks, False
632
+
633
+
634
+ _CAPTION_RE = re.compile(
635
+ r"^[^A-Za-z]*((?:fig(?:ure)?|tab(?:le)?)\.?\s*\d+)\s*[.:]\s*(\S.*)$",
636
+ re.IGNORECASE | re.DOTALL,
637
+ )
638
+
639
+
640
+ _CAPTION_RE_NORMALIZED = re.compile(
641
+ r"^[^A-Za-z]*(fig(?:ure)?|tab(?:le)?)\.?\s*(\d+)\s*[.:]\s*(\S.*)$",
642
+ re.IGNORECASE | re.DOTALL,
643
+ )
644
+
645
+
646
+ def _split_caption_label(text: str, keep_label: bool = False) -> Optional[Tuple[str, str]]:
647
+ """Split "Fig. 1. Spectrum of ..." into a label and the caption text.
648
+
649
+ By default the label is normalized to "Figure 1" or "Table 1". With
650
+ ``keep_label`` (the alto engine) it stays as printed ("Fig. 1" stays
651
+ "Fig. 1"), so the abbreviation token that the source has is not lost.
652
+ Returns None when the text does not open with a figure or table label.
653
+ """
654
+ if keep_label:
655
+ m = _CAPTION_RE.match(text)
656
+ if not m:
657
+ return None
658
+ return re.sub(r"\s+", " ", m.group(1)).strip(), m.group(2).strip()
659
+ m = _CAPTION_RE_NORMALIZED.match(text)
660
+ if not m:
661
+ return None
662
+ kind = "Figure" if m.group(1)[:3].lower() == "fig" else "Table"
663
+ return f"{kind} {m.group(2)}", m.group(3).strip()
664
+
665
+
666
+ _META_RE = re.compile(r'@\S+\.\S+|orcid\.org|ORCID:\s*\d|^Authors?\b')
667
+
668
+
669
+ def _meta_rows(blocks: list, tol: float) -> list:
670
+ """Order contact blocks by row, then left to right inside a row.
671
+
672
+ Block tops are floats that differ by fractions of a point even when two
673
+ blocks share a printed row, so sorting on the raw top scrambles a row of
674
+ side by side blocks. Blocks whose tops lie within ``tol`` of the first
675
+ block of a row belong to that row.
676
+ """
677
+ out: list = []
678
+ row: list = []
679
+ row_top = 0.0
680
+ for b in sorted(blocks, key=lambda b: (b["vpos"], b["hpos"])):
681
+ if row and b["vpos"] - row_top > tol:
682
+ out.extend(sorted(row, key=lambda r: r["hpos"]))
683
+ row = []
684
+ if not row:
685
+ row_top = b["vpos"]
686
+ row.append(b)
687
+ out.extend(sorted(row, key=lambda r: r["hpos"]))
688
+ return out
689
+
690
+
691
+ def _partition_blocks_default(blocks: list, page_h: float, page_median_fs: float,
692
+ col_start: float, col_end: float, span_threshold: float) -> list:
693
+ """Order a page's blocks as headline, contact info, body, footer (default engine)."""
694
+ _meta_re = re.compile(
695
+ r'@\S+\.\S+|orcid\.org|ORCID:\s*\d|^Authors?\b',
696
+ )
697
+ top_zone = page_h * 0.12
698
+ header_blocks = []
699
+ meta_blocks = []
700
+ body_blocks = []
701
+ footer_blocks = []
702
+ for blk in blocks:
703
+ is_wide = blk["width"] > span_threshold
704
+ is_title_font = page_median_fs > 0 and blk["fontsize"] >= page_median_fs * 1.4
705
+ if is_title_font and blk["vpos"] + blk["height"] <= col_start + page_h * 0.02:
706
+ header_blocks.append(blk)
707
+ elif is_wide and blk["vpos"] > col_end:
708
+ footer_blocks.append(blk)
709
+ elif (not is_wide
710
+ and blk["vpos"] + blk["height"] <= top_zone
711
+ and _meta_re.search(blk["text"])):
712
+ meta_blocks.append(blk)
713
+ else:
714
+ body_blocks.append(blk)
715
+
716
+ header_blocks.sort(key=lambda b: b["vpos"])
717
+ meta_blocks.sort(key=lambda b: (b["vpos"], b["hpos"]))
718
+ footer_blocks.sort(key=lambda b: b["vpos"])
719
+ return header_blocks + meta_blocks + body_blocks + footer_blocks
720
+
721
+
722
+ def _partition_blocks(blocks: list, page_h: float, page_median_fs: float,
723
+ col_start: float, col_end: float, span_threshold: float,
724
+ alto: bool = False) -> list:
725
+ """Order a page's blocks as headline, contact info, body, footer.
726
+
727
+ The default engine keeps the original partition. For the alto engine a
728
+ contact block (e-mail, ORCID, "Authors") is lifted ahead of the body only
729
+ when it stands apart. When the block just before it in reading order is an
730
+ ordinary body block of the top zone (an author name, an affiliation), the
731
+ contact block belongs to that block, so it stays where the reading order
732
+ put it and name and e-mail keep their pairing.
733
+ """
734
+ if not alto:
735
+ return _partition_blocks_default(
736
+ blocks, page_h, page_median_fs, col_start, col_end, span_threshold)
737
+ top_zone = page_h * 0.12
738
+ header_blocks, meta_blocks, body_blocks, footer_blocks = [], [], [], []
739
+ prev_kind = None
740
+ # Only the leading run of title-font blocks is the headline. A title-font
741
+ # block that follows other text in reading order (a section heading under
742
+ # the author line, a badge further down) keeps its place.
743
+ headline_open = True
744
+ for blk in blocks:
745
+ is_wide = blk["width"] > span_threshold
746
+ is_title_font = page_median_fs > 0 and blk["fontsize"] >= page_median_fs * 1.4
747
+ in_top = blk["vpos"] + blk["height"] <= top_zone
748
+ if (is_title_font and headline_open
749
+ and blk["vpos"] + blk["height"] <= col_start + page_h * 0.02):
750
+ header_blocks.append(blk)
751
+ kind = "header"
752
+ elif is_wide and blk["vpos"] > col_end:
753
+ footer_blocks.append(blk)
754
+ kind = "footer"
755
+ elif not is_wide and in_top and _META_RE.search(blk["text"]):
756
+ if prev_kind == "top_body":
757
+ body_blocks.append(blk)
758
+ kind = "top_body"
759
+ else:
760
+ meta_blocks.append(blk)
761
+ kind = "meta"
762
+ else:
763
+ body_blocks.append(blk)
764
+ kind = "top_body" if in_top else "body"
765
+ if kind != "header":
766
+ headline_open = False
767
+ prev_kind = kind
768
+ header_blocks.sort(key=lambda b: b["vpos"])
769
+ footer_blocks.sort(key=lambda b: b["vpos"])
770
+ meta_blocks = _meta_rows(meta_blocks, max(2.0, 0.5 * page_median_fs))
771
+ return header_blocks + meta_blocks + body_blocks + footer_blocks
772
+
773
+
774
+ def extract_text_with_pdfplumber(pdf_path: str,
775
+ captions_out: Optional[list] = None,
776
+ max_pages: Optional[int] = None) -> Optional[str]:
777
+ """Extract text from PDF using pdfplumber (layout-aware).
778
+
779
+ Uses recursive XY-cut tree (ported from xpdf's splitChars algorithm)
780
+ to determine reading order, then groups words into blocks and
781
+ prefixes headers with '## ' based on font size/style analysis.
782
+
783
+ Pipeline:
784
+ 1. Extract chars and words with (x0, y0, x1, y1, fontname, size)
785
+ 2. Recursive XY-cut on chars to determine reading order
786
+ 3. Map char-level lines back to word-level lines
787
+ 4. Group word lines into blocks by vertical gaps
788
+ 5. Classify blocks as header/meta/body/footer
789
+ 6. Detect headers via font size/bold heuristics
790
+
791
+ When ``captions_out`` is a list and the caption engine is on, figure and
792
+ table captions found from page geometry (see poster2json.captions) are
793
+ appended to it as ``{"kind", "label", "text", "source", "page"}`` dicts in
794
+ reading order, and each caption is replaced in the returned text by a
795
+ one-line marker (see CAPTION_RAW_MODE).
796
+ """
797
+ import pdfplumber
798
+
799
+ log(f"Attempting text extraction with pdfplumber for: {pdf_path}")
800
+ t0 = time.time()
801
+
802
+ try:
803
+ pdf = pdfplumber.open(pdf_path)
804
+ except Exception as e:
805
+ log(f"pdfplumber failed to open {pdf_path}: {e}")
806
+ return None
807
+
808
+ all_output_lines = []
809
+ use_captions = captions_out is not None and CAPTION_ENGINE
810
+ cap_counts = {"figure": 0, "table": 0}
811
+
812
+ try:
813
+ for page_no, page in enumerate(pdf.pages[:max_pages] if max_pages else pdf.pages):
814
+ page_w = page.width
815
+ page_h = page.height
816
+
817
+ from . import layout_blocks as _lb
818
+ tolerant = _layout_engine() == "alto"
819
+ try:
820
+ chars = _filter_phantom_spaces(page.chars)
821
+ except Exception:
822
+ if not tolerant:
823
+ raise
824
+ chars = list(page.chars)
825
+ if _lb.FLAGS["dedupe"] and not tolerant:
826
+ chars = _lb.dedupe_overprinted(chars)
827
+ for _i, _c in enumerate(chars):
828
+ _c["_si"] = _i # PDF stream order, used to order chars in a line
829
+
830
+ text_chars, x_tol, median_fs = _char_stats(chars, tolerant=tolerant)
831
+ log(f" x_tolerance={x_tol} (median_font={median_fs if text_chars else '?'}pt)")
832
+ if not text_chars:
833
+ continue
834
+
835
+ geo = {} if use_captions else None
836
+ all_blocks, fig_blocks, used_alto = _page_blocks(
837
+ page, chars, text_chars, x_tol, page_w, page_h, geo)
838
+ for blk in all_blocks:
839
+ blk["col"] = 0
840
+ blk["flow_idx"] = 0
841
+
842
+ if not all_blocks:
843
+ continue
844
+
845
+ all_fontsizes = [blk["fontsize"] for blk in all_blocks if blk["fontsize"] > 0]
846
+ page_median_fs = sorted(all_fontsizes)[len(all_fontsizes) // 2] if all_fontsizes else 0
847
+
848
+ text_left = min(blk["hpos"] for blk in all_blocks)
849
+ text_right = max(blk["hpos"] + blk["width"] for blk in all_blocks)
850
+ text_span = text_right - text_left
851
+ span_threshold = text_span * 0.5
852
+
853
+ min_col_block_len = 10
854
+ col_tops = {}
855
+ for blk in all_blocks:
856
+ c = blk["col"]
857
+ if blk["width"] <= span_threshold and len(blk["text"].strip()) >= min_col_block_len:
858
+ col_tops[c] = min(col_tops.get(c, float("inf")), blk["vpos"])
859
+ if not col_tops:
860
+ for blk in all_blocks:
861
+ c = blk["col"]
862
+ if blk["width"] <= span_threshold:
863
+ col_tops[c] = min(col_tops.get(c, float("inf")), blk["vpos"])
864
+ col_start = min(col_tops.values()) if col_tops else 0
865
+ col_end = max(blk["vpos"] + blk["height"] for blk in all_blocks
866
+ if blk["width"] <= span_threshold) if col_tops else page_h
867
+
868
+ all_blocks = _partition_blocks(
869
+ all_blocks, page_h, page_median_fs, col_start, col_end, span_threshold,
870
+ alto=used_alto)
871
+
872
+ # Emit figure labels as separate blocks, right after the body block
873
+ # that preceded them in the original line order (so labels are not
874
+ # glued into a paragraph, and nothing moves far from where it was
875
+ # printed).
876
+ for fb in fig_blocks:
877
+ at = 0
878
+ best = -1
879
+ for k, bk in enumerate(all_blocks):
880
+ if not bk.get("fig") and best < bk["order"] < fb["order"]:
881
+ best, at = bk["order"], k + 1
882
+ while (at < len(all_blocks) and all_blocks[at].get("fig")
883
+ and all_blocks[at]["order"] < fb["order"]):
884
+ at += 1
885
+ all_blocks.insert(at, fb)
886
+
887
+ median_fontsize = page_median_fs
888
+
889
+ if use_captions:
890
+ raise RuntimeError("caption detection is not included in PosterSentry")
891
+ _body = _lb.body_font_size(text_chars)
892
+ _found = _cap_mod.find_captions(
893
+ all_blocks,
894
+ _cap_mod.regions_from_masks(geo.get("masks") or [], _body),
895
+ geo.get("words") or [], _body, page_h)
896
+ for _c in _found:
897
+ cap_counts[_c["kind"]] += 1
898
+ _k = cap_counts[_c["kind"]]
899
+ _name = "Figure" if _c["kind"] == "figure" else "Table"
900
+ captions_out.append({
901
+ "kind": _c["kind"], "label": _c["label"],
902
+ "text": _c["text"], "source": _c["source"],
903
+ "page": page_no,
904
+ })
905
+ first = all_blocks[min(_c["blocks"])]
906
+ first["cap_marker"] = (
907
+ first.get("cap_marker", "") + ("\n" if first.get("cap_marker") else "")
908
+ + f"[{_name} caption {_k} extracted]")
909
+ first["cap_text"] = (
910
+ first.get("cap_text", "") + (" " if first.get("cap_text") else "")
911
+ + _c["text"])
912
+ for _bi in _c["blocks"]:
913
+ all_blocks[_bi]["cap"] = True
914
+
915
+ for blk in all_blocks:
916
+ _t = blk["text"].strip()
917
+ if not _t:
918
+ continue
919
+ if blk.get("cap"):
920
+ if blk.get("cap_marker"):
921
+ all_output_lines.append(blk["cap_marker"])
922
+ if CAPTION_RAW_MODE == "keep":
923
+ all_output_lines.append(_add_bidi_markers(blk["cap_text"]))
924
+ continue
925
+ if blk.get("fig"):
926
+ all_output_lines.append(_add_bidi_markers(_t))
927
+ continue
928
+
929
+ # Figure/table caption: split the "Figure N"/"Table N" label
930
+ # onto its own header line so the LLM isolates the caption as a
931
+ # caption section instead of merging it into adjacent body text.
932
+ # Captions are small-font, so the font-size header heuristic
933
+ # below never catches them; a buried short caption tanks
934
+ # section-level ROUGE (matches at ~0.2 instead of ~1.0).
935
+ _cap = _split_caption_label(_t, keep_label=used_alto)
936
+ if _cap:
937
+ all_output_lines.append(f"## {_cap[0]}")
938
+ all_output_lines.append(_add_bidi_markers(_cap[1]))
939
+ continue
940
+
941
+ # Standalone section heading printed as a bare keyword line
942
+ # (e.g. "References", "Acknowledgements"). Force a ## header so
943
+ # the LLM splits it out instead of merging it into the body.
944
+ if _t.rstrip(":.").strip().lower() in _SECTION_KEYWORDS:
945
+ all_output_lines.append(f"## {_add_bidi_markers(_t)}")
946
+ continue
947
+
948
+ # Run-on block cramming multiple sections onto one line via
949
+ # inline ALL-CAPS labels ("...REFERENCES: ... ABBREVIATIONS: ...")
950
+ # or em-dash sub-headers ("265. TWINS — Our second sample ...").
951
+ # Split into labeled sections so the LLM doesn't merge them.
952
+ _segs = _split_inline_sections(_t)
953
+ if _segs:
954
+ for _head, _body in _segs:
955
+ if _head:
956
+ all_output_lines.append(f"## {_head}")
957
+ if _body:
958
+ all_output_lines.append(_add_bidi_markers(_body))
959
+ continue
960
+
961
+ _words = _t.split()
962
+ _single_char = sum(1 for w in _words if len(w) <= 1)
963
+ if len(_words) >= 2 and _single_char > len(_words) * 0.6:
964
+ continue
965
+ if len(_t) <= 3 and not re.match(r'^[•●▪]+$', _t):
966
+ continue
967
+ _alpha_words = re.findall(r'[A-Za-z]{2,}', _t)
968
+ _starts_with_letter = bool(re.match(r'[A-Za-z]', _t))
969
+ _is_contact = bool(
970
+ re.search(r'@\S+\.\S+', _t)
971
+ or re.search(r'\+\d[\d\s]{6,}', _t)
972
+ or re.search(r'www\.', _t, re.I)
973
+ or re.search(r'https?://', _t, re.I)
974
+ )
975
+
976
+ is_header = False
977
+ # Rotated text (axis labels, side captions) is not promoted by
978
+ # weight or size; keyword headings were handled above.
979
+ _rotated = bool(blk.get("rotated"))
980
+ _is_continuation = bool(re.match(
981
+ r'(?:to|and|or|the|a|an|in|of|for|with|by|from|that|which|when)\s', _t
982
+ ))
983
+ min_words = 1 if blk["bold"] else 2
984
+ if (median_fontsize > 0 and len(_t) <= 120 and not _rotated
985
+ and _starts_with_letter and len(_alpha_words) >= min_words
986
+ and not _is_contact and not _is_continuation):
987
+ fs = blk["fontsize"]
988
+ if blk["bold"] and fs >= median_fontsize:
989
+ is_header = True
990
+ elif fs > median_fontsize * 1.3:
991
+ if len(_alpha_words) == 1:
992
+ is_header = _alpha_words[0].isupper()
993
+ else:
994
+ is_header = True
995
+
996
+ text = _add_bidi_markers(blk["text"])
997
+ if is_header:
998
+ text = f"## {text}"
999
+ all_output_lines.append(text)
1000
+
1001
+ finally:
1002
+ pdf.close()
1003
+
1004
+ elapsed = time.time() - t0
1005
+
1006
+ if not all_output_lines:
1007
+ log(f"pdfplumber produced no text for: {pdf_path}")
1008
+ return None
1009
+
1010
+ result = "\n".join(all_output_lines)
1011
+ log(f"pdfplumber extracted {len(result)} characters in {elapsed:.2f} seconds")
1012
+ return result
1013
+
1014
+
1015
+ def _add_bidi_markers(text: str) -> str:
1016
+ """Wrap RTL character runs in bidi embedding markers.
1017
+
1018
+ pdfplumber does not emit bidi markers around Hebrew, Arabic, and other
1019
+ RTL words. Without them the LLM receives bare RTL codepoints in an
1020
+ unstructured layout and fails to extract sections.
1021
+ """
1022
+ if not text:
1023
+ return text
1024
+ has_rtl = False
1025
+ for ch in text:
1026
+ if unicodedata.bidirectional(ch) in ("R", "AL"):
1027
+ has_rtl = True
1028
+ break
1029
+ if not has_rtl:
1030
+ return text
1031
+ words = text.split(" ")
1032
+ result = []
1033
+ for word in words:
1034
+ if any(unicodedata.bidirectional(c) in ("R", "AL") for c in word):
1035
+ result.append(f"‫{word}‬")
1036
+ else:
1037
+ result.append(word)
1038
+ return " ".join(result)
1039
+
src/poster_sentry/p2j/xy_cut.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recursive XY-cut reading order recovery for pdfplumber chars.
2
+
3
+ Ports xpdf's TextOutputDev::splitChars / split / findGaps algorithm
4
+ (xpdf-4.06, TextOutputDev.cc lines 1846-4363) to Python. Constants are
5
+ from the same source, expressed in fractions of average font size.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import bisect
11
+ import statistics
12
+ from dataclasses import dataclass, field
13
+ from typing import List, Tuple
14
+
15
+ MIN_GAP_AREA = 3.0
16
+ SPLIT_GAP_SLACK = 0.2
17
+ MIN_CHUNK_WIDTH = 2.0
18
+ MIN_GAP_SIZE = 0.2
19
+ BASELINE_RANGE = 0.5
20
+ DESCENT_ADJUST = 0.35
21
+
22
+
23
+ @dataclass
24
+ class Block:
25
+ kind: str # "vsplit" | "hsplit" | "leaf"
26
+ bbox: Tuple[float, float, float, float]
27
+ chars: List[dict] = field(default_factory=list)
28
+ children: List[Block] = field(default_factory=list)
29
+
30
+
31
+ def _bbox_and_stats(chars):
32
+ xs0 = [c["x0"] for c in chars]
33
+ xs1 = [c["x1"] for c in chars]
34
+ ys0 = [c["top"] for c in chars]
35
+ ys1 = [c["bottom"] for c in chars]
36
+ sizes = [c.get("size", c["bottom"] - c["top"]) for c in chars]
37
+ avg_fs = statistics.fmean(sizes) if sizes else 1.0
38
+ min_fs = min(sizes) if sizes else 1.0
39
+ return (min(xs0), min(ys0), max(xs1), max(ys1)), max(avg_fs, 0.1), max(min_fs, 0.1)
40
+
41
+
42
+ def _gaps_1d(chars, axis):
43
+ if axis == "x":
44
+ intervals = sorted((c["x0"], c["x1"]) for c in chars)
45
+ else:
46
+ intervals = sorted((c["top"], c["bottom"]) for c in chars)
47
+ gaps = []
48
+ cur_end = intervals[0][1]
49
+ for a, b in intervals[1:]:
50
+ if a > cur_end + 0.01:
51
+ gaps.append(((cur_end + a) / 2.0, a - cur_end))
52
+ cur_end = max(cur_end, b)
53
+ return gaps
54
+
55
+
56
+ def _chars_in(chars, x0, y0, x1, y1):
57
+ out = []
58
+ for c in chars:
59
+ cx = (c["x0"] + c["x1"]) / 2
60
+ cy = c["bottom"] - DESCENT_ADJUST * (c["bottom"] - c["top"])
61
+ if x0 - 0.5 <= cx < x1 + 0.5 and y0 - 0.5 <= cy < y1 + 0.5:
62
+ out.append(c)
63
+ return out
64
+
65
+
66
+ def _partition(chars, bounds, axis):
67
+ """Split `chars` into one list per [bounds[i], bounds[i+1]) interval in a
68
+ single pass, keyed by the same center coordinate `_chars_in` uses.
69
+
70
+ Equivalent to calling `_chars_in` once per interval, because cut positions
71
+ always land inside whitespace gaps and no char center is within the old
72
+ 0.5pt boundary slack of a cut, so assignment is unambiguous. Runs in
73
+ O(n log k) instead of O(n*k), and assigns each char to exactly one child
74
+ (the old per-interval slack could place a char into two children, which is
75
+ what made the recursion blow up on dense pages)."""
76
+ n_intervals = len(bounds) - 1
77
+ buckets = [[] for _ in range(n_intervals)]
78
+ if n_intervals == 1:
79
+ buckets[0].extend(chars)
80
+ return buckets
81
+ for c in chars:
82
+ if axis == "x":
83
+ coord = (c["x0"] + c["x1"]) / 2.0
84
+ else:
85
+ coord = c["bottom"] - DESCENT_ADJUST * (c["bottom"] - c["top"])
86
+ i = bisect.bisect_right(bounds, coord) - 1
87
+ if i < 0:
88
+ i = 0
89
+ elif i >= n_intervals:
90
+ i = n_intervals - 1
91
+ buckets[i].append(c)
92
+ return buckets
93
+
94
+
95
+ def _min_chunk_width(chars, gaps, max_g, avg_fs, bbox):
96
+ x0, _, x1, _ = bbox
97
+ slack = SPLIT_GAP_SLACK * avg_fs
98
+ cuts = sorted(g[0] for g in gaps if g[1] > max_g - slack)
99
+ bounds = [x0] + cuts + [x1]
100
+ if len(bounds) < 2:
101
+ return 1e9
102
+ return min(b - a for a, b in zip(bounds[:-1], bounds[1:]))
103
+
104
+
105
+ def split_block(chars, depth=0) -> Block:
106
+ if not chars:
107
+ return Block("leaf", (0, 0, 0, 0), [], [])
108
+
109
+ if len(chars) <= 2:
110
+ bbox, _, _ = _bbox_and_stats(chars)
111
+ return Block("leaf", bbox, sorted(chars, key=lambda c: (c["bottom"], c["x0"])), [])
112
+
113
+ bbox, avg_fs, min_fs = _bbox_and_stats(chars)
114
+ x0, y0, x1, y1 = bbox
115
+ block_h = max(y1 - y0, 0.1)
116
+ block_w = max(x1 - x0, 0.1)
117
+
118
+ if depth > 50:
119
+ return Block("leaf", bbox, sorted(chars, key=lambda c: (c["bottom"], c["x0"])), [])
120
+
121
+ vgaps = _gaps_1d(chars, "x")
122
+ hgaps = _gaps_1d(chars, "y")
123
+ max_v = max((g[1] for g in vgaps), default=0.0)
124
+ max_h = max((g[1] for g in hgaps), default=0.0)
125
+
126
+ gap_threshold_v = MIN_GAP_AREA * (avg_fs ** 2) / block_h
127
+ min_gap = MIN_GAP_SIZE * min_fs
128
+ min_chunk = MIN_CHUNK_WIDTH * avg_fs
129
+
130
+ is_single_line = block_h < 1.5 * avg_fs
131
+
132
+ do_vsplit = (
133
+ not is_single_line
134
+ and max_v > min_gap
135
+ and max_v > gap_threshold_v
136
+ and _min_chunk_width(chars, vgaps, max_v, avg_fs, bbox) > min_chunk
137
+ )
138
+
139
+ gap_threshold_h = MIN_GAP_AREA * (avg_fs ** 2) / block_w
140
+ do_hsplit = (not do_vsplit) and max_h > min_gap and max_h > gap_threshold_h
141
+
142
+ if do_vsplit:
143
+ slack = SPLIT_GAP_SLACK * avg_fs
144
+ cuts = sorted(g[0] for g in vgaps if g[1] > max_v - slack)
145
+ bounds = [x0] + cuts + [x1]
146
+ children = []
147
+ for sub in _partition(chars, bounds, "x"):
148
+ if sub:
149
+ children.append(split_block(sub, depth + 1))
150
+ if len(children) <= 1:
151
+ return Block("leaf", bbox, sorted(chars, key=lambda c: (c["bottom"], c["x0"])), [])
152
+ return Block("vsplit", bbox, [], children)
153
+
154
+ if do_hsplit:
155
+ slack = SPLIT_GAP_SLACK * avg_fs
156
+ cuts = sorted(g[0] for g in hgaps if g[1] > max_h - slack)
157
+ bounds = [y0] + cuts + [y1]
158
+ children = []
159
+ for sub in _partition(chars, bounds, "y"):
160
+ if sub:
161
+ children.append(split_block(sub, depth + 1))
162
+ if len(children) <= 1:
163
+ return Block("leaf", bbox, sorted(chars, key=lambda c: (c["bottom"], c["x0"])), [])
164
+ return Block("hsplit", bbox, [], children)
165
+
166
+ return Block("leaf", bbox, sorted(chars, key=lambda c: (c["bottom"], c["x0"])), [])
167
+
168
+
169
+ def _cluster_lines(chars):
170
+ if not chars:
171
+ return []
172
+ sizes = [c.get("size", c["bottom"] - c["top"]) for c in chars]
173
+ avg_fs = statistics.fmean(sizes) if sizes else 1.0
174
+ tol = BASELINE_RANGE * max(avg_fs, 1.0)
175
+ chars = sorted(chars, key=lambda c: (c["bottom"], c["x0"]))
176
+ lines = []
177
+ cur = [chars[0]]
178
+ cur_base = chars[0]["bottom"]
179
+ for c in chars[1:]:
180
+ if abs(c["bottom"] - cur_base) <= tol:
181
+ cur.append(c)
182
+ cur_base = statistics.fmean(ch["bottom"] for ch in cur)
183
+ else:
184
+ lines.append(sorted(cur, key=lambda c: c["x0"]))
185
+ cur = [c]
186
+ cur_base = c["bottom"]
187
+ if cur:
188
+ lines.append(sorted(cur, key=lambda c: c["x0"]))
189
+ return lines
190
+
191
+
192
+ def _promote_spanning_leaves(block, page_width):
193
+ """Promote wide leaves nested in vsplits to hsplit siblings.
194
+
195
+ Handles layouts where a spanning block (title, footnote, sidebar)
196
+ ends up inside a column split because its y-position overlaps the
197
+ column region. Promotes any leaf wider than 0.7 × page_width out
198
+ of its vsplit parent and re-wraps as an hsplit ordered by y.
199
+ """
200
+ if block.kind == "leaf":
201
+ return block
202
+ block.children = [_promote_spanning_leaves(c, page_width) for c in block.children]
203
+ if block.kind != "vsplit":
204
+ return block
205
+
206
+ wide_threshold = 0.7 * page_width
207
+ wide = []
208
+ narrow = []
209
+ for child in block.children:
210
+ child_w = child.bbox[2] - child.bbox[0]
211
+ if child.kind == "leaf" and child_w > wide_threshold:
212
+ wide.append(child)
213
+ else:
214
+ narrow.append(child)
215
+
216
+ if not wide or not narrow:
217
+ return block
218
+
219
+ all_children = sorted(block.children, key=lambda c: c.bbox[1])
220
+ new_children = []
221
+ col_group = []
222
+ for child in all_children:
223
+ if child in wide:
224
+ if col_group:
225
+ if len(col_group) == 1:
226
+ new_children.append(col_group[0])
227
+ else:
228
+ xs = [c.bbox[0] for c in col_group]
229
+ ys = [c.bbox[1] for c in col_group]
230
+ xe = [c.bbox[2] for c in col_group]
231
+ ye = [c.bbox[3] for c in col_group]
232
+ new_children.append(Block(
233
+ "vsplit", (min(xs), min(ys), max(xe), max(ye)), [], col_group
234
+ ))
235
+ col_group = []
236
+ new_children.append(child)
237
+ else:
238
+ col_group.append(child)
239
+ if col_group:
240
+ if len(col_group) == 1:
241
+ new_children.append(col_group[0])
242
+ else:
243
+ xs = [c.bbox[0] for c in col_group]
244
+ ys = [c.bbox[1] for c in col_group]
245
+ xe = [c.bbox[2] for c in col_group]
246
+ ye = [c.bbox[3] for c in col_group]
247
+ new_children.append(Block(
248
+ "vsplit", (min(xs), min(ys), max(xe), max(ye)), [], col_group
249
+ ))
250
+
251
+ if len(new_children) == 1:
252
+ return new_children[0]
253
+ return Block("hsplit", block.bbox, [], new_children)
254
+
255
+
256
+ def _merge_bottom_region(block, page_height):
257
+ """Merge bottom portions of top-level vsplits into horizontal reading order.
258
+
259
+ In academic posters, the bottom region often has sections (Conclusion,
260
+ References, Acknowledgements) that should be read top-to-bottom across
261
+ the full width, not column-by-column.
262
+ """
263
+ if block.kind == "leaf":
264
+ return block
265
+ block.children = [_merge_bottom_region(c, page_height) for c in block.children]
266
+ if block.kind != "vsplit" or len(block.children) < 2:
267
+ return block
268
+
269
+ if block.bbox[1] < page_height * 0.65:
270
+ return block
271
+
272
+ reordered = sorted(block.children, key=lambda c: c.bbox[1])
273
+ return Block("hsplit", block.bbox, [], reordered)
274
+
275
+
276
+ def traverse(block: Block) -> list:
277
+ if block.kind == "leaf":
278
+ return _cluster_lines(block.chars)
279
+ out = []
280
+ for ch in block.children:
281
+ out.extend(traverse(ch))
282
+ return out
283
+
284
+
285
+ def iter_leaves(block: Block):
286
+ """Yield the leaf blocks of an XY-cut tree in reading order."""
287
+ for leaf, _path in iter_leaves_with_path(block):
288
+ yield leaf
289
+
290
+
291
+ def iter_leaves_with_path(block: Block, path: tuple = ()):
292
+ """Yield (leaf, column path) in reading order.
293
+
294
+ The path records, for every vsplit (column split) on the way down from the
295
+ root, which child the leaf lives under. Two leaves with the same path are
296
+ stacked vertically inside one column region; different paths mean the
297
+ reading order jumps between columns.
298
+ """
299
+ if block.kind == "leaf":
300
+ yield block, path
301
+ return
302
+ for i, ch in enumerate(block.children):
303
+ sub = path + ((id(block), i),) if block.kind == "vsplit" else path
304
+ yield from iter_leaves_with_path(ch, sub)
305
+
306
+
307
+ def _build_tree(raw_chars: list, page_width: float, page_height: float):
308
+ chars = [c for c in raw_chars if c.get("text", "").strip()]
309
+ if not chars:
310
+ return None
311
+ tree = split_block(chars)
312
+ if page_width > 0:
313
+ tree = _promote_spanning_leaves(tree, page_width)
314
+ if page_height > 0:
315
+ tree = _merge_bottom_region(tree, page_height)
316
+ return tree
317
+
318
+
319
+ def chars_to_leaves(raw_chars: list, page_width: float = 0,
320
+ page_height: float = 0):
321
+ """Return (leaf char lists, column region id per leaf), in reading order.
322
+
323
+ Unlike chars_to_reading_order this keeps the XY-cut structure, so callers
324
+ can refuse to merge text across column-region boundaries. Region ids are
325
+ small ints, equal for leaves with the same column path.
326
+ """
327
+ tree = _build_tree(raw_chars, page_width, page_height)
328
+ if tree is None:
329
+ return [], []
330
+ leaves, regions, seen = [], [], {}
331
+ for leaf, path in iter_leaves_with_path(tree):
332
+ if not leaf.chars:
333
+ continue
334
+ leaves.append(leaf.chars)
335
+ regions.append(seen.setdefault(path, len(seen)))
336
+ return leaves, regions
337
+
338
+
339
+ def chars_to_leaf_lines(raw_chars: list, page_width: float = 0,
340
+ page_height: float = 0):
341
+ """Like chars_to_reading_order, but also return a column region id per line."""
342
+ tree = _build_tree(raw_chars, page_width, page_height)
343
+ if tree is None:
344
+ return [], []
345
+ lines, ids, seen = [], [], {}
346
+ for leaf, path in iter_leaves_with_path(tree):
347
+ rid = seen.setdefault(path, len(seen))
348
+ for ln in _cluster_lines(leaf.chars):
349
+ lines.append(ln)
350
+ ids.append(rid)
351
+ return lines, ids
352
+
353
+
354
+ def chars_to_reading_order(raw_chars: list, page_width: float = 0,
355
+ page_height: float = 0) -> list:
356
+ tree = _build_tree(raw_chars, page_width, page_height)
357
+ if tree is None:
358
+ return []
359
+ return traverse(tree)