kakemono/analysis/page.rs
1//! Per-page working data and document-wide statistics.
2//!
3//! [`PageData`] is the mutable working copy of one page that the analysis
4//! stages pass along; [`DocStats`] holds the few document-wide measurements
5//! (body font size, body font, line pitch) that most later thresholds are
6//! expressed relative to.
7
8use super::lines::{LinesConfig, build_lines};
9use crate::backend::{ImageBox, PathBox, RawPage};
10use crate::common::geom::{Rect, weighted_mode};
11use crate::model::{Line, RotatedText};
12use std::collections::HashMap;
13
14/// Tuning parameters of the document-wide page statistics. Part of [`LayoutConfig`](crate::config::LayoutConfig).
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct PageConfig {
17 /// Bin width (in points) of the font-size histogram whose mode is the
18 /// body size. A quarter point merges sizes that differ only by rounding
19 /// in the PDF while keeping 9 pt and 10 pt apart.
20 pub body_size_bin_pt: f32,
21 /// Body size (in points) assumed when the document has no text at all.
22 pub default_body_size_pt: f32,
23 /// Largest difference (in points) between a line's size and the body
24 /// size for the line to count as running text.
25 pub body_size_tolerance_pt: f32,
26 /// Lines with at most this many glyphs are ignored when measuring the
27 /// leading: short lines (headings, equation numbers, labels) are often
28 /// not part of a regular paragraph.
29 pub leading_min_glyphs_count: usize,
30 /// How many following body lines are inspected when looking for the
31 /// next line below a given one.
32 pub leading_lookahead_count: usize,
33 /// A vertical distance above this (in body sizes) ends the search for
34 /// the line below: anything further away is a paragraph or section gap,
35 /// not the line pitch.
36 pub leading_max_gap_em: f32,
37 /// A vertical distance must exceed this (in body sizes) to count as a
38 /// line pitch; smaller distances are lines of a neighbouring column or
39 /// fragments on (nearly) the same baseline.
40 pub leading_min_gap_em: f32,
41 /// Minimum horizontal overlap of two lines, as a fraction of the
42 /// narrower one, for them to count as vertically adjacent lines of the
43 /// same column.
44 pub leading_overlap_ratio: f32,
45 /// Bin width (in points) of the histogram of line pitches.
46 pub leading_bin_pt: f32,
47 /// Leading (in body sizes) assumed when no pair of adjacent body lines
48 /// was found; 1.2 is the usual default line spacing of typesetters.
49 pub default_leading_em: f32,
50 /// Two adjacent body lines are lines of one paragraph when their
51 /// baseline distance is at most this many leadings ...
52 pub line_pitch_max_leading: f32,
53 /// ... and lines of two paragraphs set apart by a blank space when it
54 /// is at least this many leadings (and at most
55 /// [`PageConfig::leading_max_gap_em`]).
56 pub para_space_min_leading: f32,
57 /// The document separates its paragraphs by space (a novel made in
58 /// Word, with no first-line indent) when at least this share of the
59 /// adjacent body lines are spaced paragraphs ...
60 pub spaced_paragraphs_min_ratio: f32,
61 /// ... and at least this share of those spaced distances are the same
62 /// (within [`PageConfig::para_space_tolerance_leading`]): a blank line
63 /// or a fixed space after each paragraph, not the varied gaps around
64 /// the headings, equations and figures of a paper.
65 pub para_space_regular_min_ratio: f32,
66 /// Width (in leadings) of the window in which spaced distances count
67 /// as the same.
68 pub para_space_tolerance_leading: f32,
69}
70
71impl Default for PageConfig {
72 fn default() -> Self {
73 Self {
74 body_size_bin_pt: 0.25,
75 default_body_size_pt: 10.0,
76 body_size_tolerance_pt: 0.3,
77 leading_min_glyphs_count: 20,
78 leading_lookahead_count: 12,
79 leading_max_gap_em: 2.5,
80 leading_min_gap_em: 0.7,
81 leading_overlap_ratio: 0.5,
82 leading_bin_pt: 0.1,
83 default_leading_em: 1.2,
84 line_pitch_max_leading: 1.15,
85 para_space_min_leading: 1.5,
86 spaced_paragraphs_min_ratio: 0.2,
87 para_space_regular_min_ratio: 0.8,
88 para_space_tolerance_leading: 0.1,
89 }
90 }
91}
92
93/// The working data of one page: its size, its text lines (built from the
94/// glyphs), rotated text runs, images and vector paths. Later stages remove
95/// or rewrite lines in place.
96pub struct PageData {
97 /// Zero-based page number in the document.
98 pub index: usize,
99 /// Page width in points.
100 pub width: f32,
101 /// Page height in points.
102 pub height: f32,
103 /// Horizontal text lines, sorted by baseline then left edge.
104 pub lines: Vec<Line>,
105 /// Text runs that are not horizontal (rotated margin stamps, axis labels).
106 pub rotated: Vec<RotatedText>,
107 /// Raster images drawn on the page.
108 pub images: Vec<ImageBox>,
109 /// Bounding boxes of vector paths (rules, figure strokes, table borders).
110 pub paths: Vec<PathBox>,
111 /// Rules drawn as stretched pictures of one pixel (table rules of some
112 /// typesetters); see [`RawPage::pixel_rules`].
113 pub pixel_rules: Vec<PathBox>,
114 /// The last page of the document (where a book has its back cover).
115 pub last: bool,
116 /// Lines dropped by [`PageData::drop_lines`], still counted by
117 /// [`PageData::line_count`].
118 dropped_lines: usize,
119}
120
121impl PageData {
122 /// Builds the working data of a page from what the backend extracted,
123 /// grouping the glyphs into lines with `lines_cfg`.
124 pub fn from_raw(raw: RawPage, lines_cfg: &LinesConfig) -> Self {
125 let (lines, rotated) = build_lines(&raw, lines_cfg);
126 Self {
127 index: raw.index,
128 width: raw.width,
129 height: raw.height,
130 lines,
131 rotated,
132 images: raw.images,
133 paths: raw.paths,
134 pixel_rules: raw.pixel_rules,
135 last: false,
136 dropped_lines: 0,
137 }
138 }
139
140 /// Drops the lines of the page once it is laid out: its blocks hold
141 /// copies of the lines they need, and the later stages only read how
142 /// many lines the page had ([`PageData::line_count`]).
143 pub fn drop_lines(&mut self) {
144 self.dropped_lines += self.lines.len();
145 self.lines = Vec::new();
146 }
147
148 /// Number of lines of the page, those dropped by
149 /// [`PageData::drop_lines`] included.
150 pub fn line_count(&self) -> usize {
151 self.dropped_lines + self.lines.len()
152 }
153
154 /// The rectangle covering the whole page.
155 pub fn rect(&self) -> Rect {
156 Rect::new(0.0, 0.0, self.width, self.height)
157 }
158}
159
160/// Document-wide measurements of the running text.
161#[derive(Debug, Clone, Copy)]
162pub struct DocStats {
163 /// Font size of the running text.
164 pub body_size: f32,
165 /// Font index (into the document's font table) used by most running text.
166 pub body_font: u16,
167 /// Baseline distance of the running text.
168 pub leading: f32,
169 /// The paragraphs are separated by a blank space (see
170 /// [`PageConfig::spaced_paragraphs_min_ratio`]): a group of lines set
171 /// close together is then a single paragraph.
172 pub spaced_paragraphs: bool,
173}
174
175/// Measures the body size, body font and leading of the document.
176///
177/// The body size is the glyph-weighted most common line size; the body font
178/// is the font with most glyphs among lines of that size; the leading is the
179/// most common baseline distance between adjacent body lines. Each falls
180/// back to a default (see [`PageConfig`]) when the document has no text.
181/// The share of those distances that are a blank line rather than the
182/// leading tells whether paragraphs are separated by space.
183pub fn compute_stats(pages: &[PageData], cfg: &PageConfig) -> DocStats {
184 let body_size = measure_body_size(pages, cfg);
185 let body_font = find_body_font(pages, body_size, cfg);
186 let pitches = adjacent_pitches(pages, body_size, cfg);
187 let leading = weighted_mode(
188 pitches.iter().map(|&dy| (dy, 1.0)),
189 cfg.leading_bin_pt,
190 body_size * cfg.default_leading_em,
191 );
192 let lines = pitches
193 .iter()
194 .filter(|&&dy| dy <= cfg.line_pitch_max_leading * leading)
195 .count();
196 let mut spaced: Vec<f32> = pitches
197 .iter()
198 .copied()
199 .filter(|&dy| dy >= cfg.para_space_min_leading * leading)
200 .collect();
201 spaced.sort_by(f32::total_cmp);
202 let regular = most_within(&spaced, cfg.para_space_tolerance_leading * leading);
203 DocStats {
204 body_size,
205 body_font,
206 leading,
207 spaced_paragraphs: spaced.len() as f32
208 >= cfg.spaced_paragraphs_min_ratio * (lines + spaced.len()).max(1) as f32
209 && regular as f32 >= cfg.para_space_regular_min_ratio * spaced.len() as f32,
210 }
211}
212
213/// Most common line size, each line weighted by its number of glyphs.
214fn measure_body_size(pages: &[PageData], cfg: &PageConfig) -> f32 {
215 weighted_mode(
216 pages
217 .iter()
218 .flat_map(|page| page.lines.iter())
219 .map(|line| (line.size, line.char_count() as f32)),
220 cfg.body_size_bin_pt,
221 cfg.default_body_size_pt,
222 )
223}
224
225/// Font with the most glyphs among the lines set in the body size (the
226/// lower font number on a tie), or 0 when there are no such lines.
227fn find_body_font(pages: &[PageData], body_size: f32, cfg: &PageConfig) -> u16 {
228 let mut fonts: HashMap<u16, usize> = HashMap::new();
229 for line in pages.iter().flat_map(|page| page.lines.iter()) {
230 if (line.size - body_size).abs() < cfg.body_size_tolerance_pt {
231 *fonts.entry(line.font).or_default() += line.char_count();
232 }
233 }
234 fonts
235 .into_iter()
236 .max_by_key(|&(font, count)| (count, std::cmp::Reverse(font)))
237 .map(|(font, _)| font)
238 .unwrap_or(0)
239}
240
241/// The largest number of the `sorted` values that fit in a window of
242/// `width`.
243fn most_within(sorted: &[f32], width: f32) -> usize {
244 let mut best = 0;
245 let mut start = 0;
246 for (end, &value) in sorted.iter().enumerate() {
247 while value - sorted[start] > width {
248 start += 1;
249 }
250 best = best.max(end + 1 - start);
251 }
252 best
253}
254
255/// Baseline distances between vertically adjacent body lines that overlap
256/// horizontally (up to [`PageConfig::leading_max_gap_em`]); their mode is
257/// the leading.
258fn adjacent_pitches(pages: &[PageData], body_size: f32, cfg: &PageConfig) -> Vec<f32> {
259 let mut gaps: Vec<f32> = Vec::new();
260 for page in pages {
261 let body: Vec<&Line> = page
262 .lines
263 .iter()
264 .filter(|line| {
265 (line.size - body_size).abs() < cfg.body_size_tolerance_pt
266 && line.char_count() > cfg.leading_min_glyphs_count
267 })
268 .collect();
269 for (i, upper) in body.iter().enumerate() {
270 for lower in body[i + 1..].iter().take(cfg.leading_lookahead_count) {
271 let dy = lower.baseline - upper.baseline;
272 if dy > cfg.leading_max_gap_em * body_size {
273 break;
274 }
275 if dy > cfg.leading_min_gap_em * body_size
276 && upper.bbox.x_overlap(&lower.bbox)
277 > cfg.leading_overlap_ratio * upper.bbox.width().min(lower.bbox.width())
278 {
279 gaps.push(dy);
280 break;
281 }
282 }
283 }
284 }
285 gaps
286}
287
288#[cfg(test)]
289mod tests {
290 use super::most_within;
291
292 #[test]
293 fn spaced_distances_of_a_novel_are_regular() {
294 // A blank line after every paragraph: the same distance each time.
295 assert_eq!(most_within(&[32.1, 32.2, 32.2, 32.2, 32.3], 1.6), 5);
296 // The gaps around a paper's headings, equations and figures vary.
297 assert_eq!(most_within(&[16.0, 18.5, 20.0, 22.0, 24.5], 1.1), 1);
298 assert_eq!(most_within(&[], 1.0), 0);
299 }
300}