File size: 5,055 Bytes
3a77415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python3
"""Layout checks that the overfull-box test does not see (round 24): every caption's opening words and every table
row's plain text must appear in the pdftotext of the PDF; no word may lie below the text block except the page
number; the LaTeX log must have no "Float too large", no "Overfull \\vbox" and no "Overfull \\hbox".

usage: check_layout.py [--latex DIR] PDF LOG [PDF LOG ...]   (paper sources: DIR, else ../latex or ../paper)"""
from __future__ import annotations

import re
import subprocess
import sys
from pathlib import Path

_HERE = Path(__file__).resolve().parent
# paper sources: --latex DIR, else ../latex (repository) or ../paper (bundle copy: scripts/check_layout.py, paper/)
LATEX = next((p for p in (_HERE.parent / "latex", _HERE.parent / "paper") if (p / "main.tex").exists()), _HERE.parent / "paper")
BOTTOM = 788.0     # text block ends near y 774-777 (A4, 2.4 cm margin); the page number sits at y 796-806


def sources() -> list[Path]:
    m = (LATEX / "main.tex").read_text(errors="replace")
    used = set(re.findall(r"^\s*\\input\{sections/([^}]+)\}", m, re.M))   # only the sections the PDF includes
    return [LATEX / "main.tex"] + sorted(LATEX / "sections" / (u if u.endswith(".tex") else u + ".tex") for u in used)


def plain_words(tex: str) -> list[str]:
    t = re.sub(r"%.*", "", tex)
    t = re.sub(r"\$[^$]*\$", " ", t)
    t = re.sub(r"\\(cite[a-z]*|cref|Cref|ref|label|eqref)\{[^}]*\}", " ", t)
    t = re.sub(r"\\[a-zA-Z@]+\*?(\[[^\]]*\])?", " ", t)       # commands (their arguments stay as text)
    t = t.replace("\\_", "_").replace("{", " ").replace("}", " ").replace("~", " ")
    t = t.replace("-", " ").replace("\\allowbreak", " ")
    return re.findall(r"[A-Za-z][A-Za-z']{2,}", t)


def pdf_text(pdf: str) -> str:
    t = subprocess.run(["pdftotext", pdf, "-"], capture_output=True, text=True).stdout
    t = re.sub(r"-\s*\n", "", t).replace("-", " ")      # line-end hyphenation rejoined; other hyphens split words
    t = t.replace("\u2019", "'").replace("\u2018", "'")
    t = t.replace("\ufb01", "fi").replace("\ufb02", "fl").replace("\ufb00", "ff").replace("\ufb03", "ffi")
    return re.sub(r"\s+", " ", t)


def seq_in(words: list[str], text: str) -> bool:
    pat = r"[\W_]+(?:\w+[\W_]+){0,3}?".join(re.escape(w) for w in words)
    return re.search(pat, text) is not None


def captions() -> list[tuple[str, list[str]]]:
    out = []
    for f in sources():
        s = f.read_text(errors="replace")
        for m in re.finditer(r"\\caption\{", s):
            first = s[m.end():m.end() + 400].split(". ")[0]
            w = plain_words(first)[:4]
            if len(w) >= 2:
                out.append((f"{f.name}: {first[:50]!r}", w))
    return out


def table_rows() -> list[tuple[str, list[str]]]:
    out = []
    for f in sources():
        s = f.read_text(errors="replace")
        for tb in re.finditer(r"\\begin\{tabular[x]?\}.*?\\end\{tabular[x]?\}", s, re.S):
            for row in tb.group(0).split("\\\\"):
                if "\\toprule" in row or "\\multicolumn" in row:
                    continue
                w = plain_words(re.sub(r"\\[cm]?i?d?rule(\([^)]*\))?(\{[^}]*\})?", " ", row).split("&")[0])[:3]
                if len(w) >= 2:
                    out.append((f"{f.name}: {row.strip()[:50]!r}", w))
    return out


def below_text_block(pdf: str) -> list[str]:
    x = subprocess.run(["pdftotext", "-bbox", pdf, "-"], capture_output=True, text=True).stdout
    bad, page = [], 0
    for ln in x.splitlines():
        if "<page " in ln:
            page += 1
        m = re.search(r'yMax="([0-9.]+)">([^<]*)</word>', ln)
        if m and float(m.group(1)) > BOTTOM and not re.fullmatch(r"\d{1,3}", m.group(2)):
            bad.append(f"p{page}: {m.group(2)!r} at y {float(m.group(1)):.0f}")
    return bad


def main() -> int:
    global LATEX
    args = sys.argv[1:]
    if args[:1] == ["--latex"]:
        LATEX, args = Path(args[1]), args[2:]
    caps, rows, rc = captions(), table_rows(), 0
    for pdf, log in zip(args[::2], args[1::2]):
        text = pdf_text(pdf)
        lg = Path(log).read_text(errors="replace")
        miss_c = [n for n, w in caps if not seq_in(w, text)]
        miss_r = [n for n, w in rows if not seq_in(w, text)]
        below = below_text_block(pdf)
        counts = dict(float_too_large=lg.count("Float too large"), overfull_vbox=lg.count("Overfull \\vbox"),
                      overfull_hbox=lg.count("Overfull \\hbox"))
        print(f"{Path(pdf).name}: captions {len(caps) - len(miss_c)}/{len(caps)} found; table rows "
              f"{len(rows) - len(miss_r)}/{len(rows)} found; words below the text block {len(below)}; {counts}")
        for n in miss_c[:20]:
            print("  caption missing:", n)
        for n in miss_r[:20]:
            print("  table row missing:", n)
        for b in below[:20]:
            print("  below text block:", b)
        if miss_c or miss_r or below or any(counts.values()):
            rc = 1
    return rc


if __name__ == "__main__":
    sys.exit(main())