← Files TeX64ARCHIVED FILE

skills/tablify/scripts/build.py

16.1 KB · Nov 27, 2026 · 18:48 UTC

↓ Download file

See the change to this file →

#!/usr/bin/env python3
"""Compile a tabularray table into a ready-to-insert bundle and check it against
its source data, the source image and the user's requests.

Input
  TAB.tblr            one tblr / longtblr / talltblr environment, nothing else.
  TAB.preamble.tex    optional: \\usepackage / \\UseTblrLibrary lines it needs
                      (picked up automatically next to TAB.tblr, or --preamble).
  TAB.cells.json      optional (written by draft.py): the cells as read from the
                      source.  Every non-empty cell must appear in the output.
  TAB.request.md      optional: the user's requests and how each was applied
                      (references/requests.md).  Open ones are listed every build.

Output (in --outdir, default: next to TAB.tblr)
  TAB.standalone.tex  compilable on its own (\\input{TAB.tblr})
  TAB.pdf / .png / .svg
  TAB.snippet.tex     table environment + preamble lines to paste
  _check/TAB-compare.png   source | render side by side           (with --ref)
  _check/TAB-overlay.png   source (red) x render (blue), ink boxes fitted onto
                           each other, so rules and cell positions line up (with --ref)
  _build/             intermediate files (safe to delete)

Usage
  build.py TAB.tblr [--preamble P.tex] [--ref IMG] [--engine auto|lualatex|pdflatex|xelatex]
           [--dpi 220] [--caption TEXT] [--label tab:x] [--doc main.tex] [--outdir DIR]
           [--textwidth-cm 15.5]

  --textwidth-cm  warn when the table is wider than the host's text width.
"""
import argparse
import json
import os
import re
import shutil
import sys
import unicodedata

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _common import (check_name, check_path, need, posix_rel, read_text,  # noqa: E402
                     report_requests, run, strip_comments, write_text)

CJK = re.compile(r"[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]")
CTRL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
ENV = re.compile(r"\\begin\s*\{(tblr|longtblr|talltblr)\}")
MARK = "% generated by tablify build.py"


def tex_errors(log):
    out, lines = [], log.splitlines()
    for i, l in enumerate(lines):
        if l.startswith("!") or re.match(r"^\S+\.(tex|tblr):\d+:", l):
            out.extend(lines[i:i + 4])
            out.append("")
    for l in lines:
        if "Missing character" in l:
            out.append("WARNING " + l.strip())
        if "Overfull \\hbox" in l:
            out.append("WARNING " + l.strip())
    return "\n".join(out[:80])


def pdf_size_cm(pdf):
    if shutil.which("pdfinfo") is None:
        return None
    r = run(["pdfinfo", pdf], check=False)
    m = re.search(r"Page size:\s+([\d.]+) x ([\d.]+) pts", r.stdout)
    return (float(m.group(1)) / 72 * 2.54, float(m.group(2)) / 72 * 2.54) if m else None


def doc(preamble_lines, body, engine, cjk, long_table):
    # longtblr breaks pages, which standalone cannot hold: use a tall article page instead
    if long_table:
        pre = [MARK, "\\documentclass{article}",
               "\\usepackage[paperwidth=30cm,paperheight=200cm,margin=5mm]{geometry}",
               "\\pagestyle{empty}"]
    else:
        pre = [MARK, "\\documentclass[border=3pt]{standalone}"]
    if cjk:
        pre.append("\\usepackage{luatexja}" if engine == "lualatex" else
                   "\\usepackage{xeCJK}" if engine == "xelatex" else "")
    pre += preamble_lines
    return "\n".join([p for p in pre if p] + ["\\begin{document}", body, "\\end{document}", ""])


def compile_tex(engine, texname, cwd):
    r = run([engine, "-interaction=nonstopmode", "-halt-on-error", "-file-line-error",
             "-output-directory=_build", texname], cwd=cwd, check=False)
    stem = os.path.splitext(texname)[0]
    logp = os.path.join(cwd, "_build", stem + ".log")
    log = read_text(logp) if os.path.exists(logp) else r.stdout
    pdf = os.path.join(cwd, "_build", stem + ".pdf")
    return (r.returncode == 0 and os.path.exists(pdf)), pdf, log


def check_source(path, text):
    m = CTRL.search(text)
    if m:
        line = text.count("\n", 0, m.start()) + 1
        sys.exit(f"error: {path}:{line} contains control character {m.group()!r}. "
                 "Write TeX files with an editor or printf '%s\\n', not echo.")


def split_rows(body):
    """Rows and cells of the tblr body (outer {...} spec removed).  Good enough
    for counting: & and \\\\ inside braces are ignored."""
    m = ENV.search(body)
    s = body[m.end():]
    s = s[:s.rfind("\\end{")]
    # skip optional [outer spec] and the {inner spec}
    s = s.lstrip()
    for opener, closer in (("[", "]"), ("{", "}")):
        if s.startswith(opener):
            depth = 0
            for k, ch in enumerate(s):
                depth += ch == opener
                depth -= ch == closer
                if depth == 0:
                    s = s[k + 1:].lstrip()
                    break
    rows, cell, cells, depth, k = [], "", [], 0, 0
    while k < len(s):
        ch = s[k]
        if ch == "\\" and k + 1 < len(s):
            if s[k + 1] == "\\" and depth == 0:
                cells.append(cell)
                rows.append(cells)
                cell, cells = "", []
                k += 2
                # swallow an optional [length] after \\
                mm = re.match(r"\s*\[[^\]]*\]", s[k:])
                if mm:
                    k += mm.end()
                continue
            cell += s[k:k + 2]
            k += 2
            continue
        if ch == "{":
            depth += 1
        elif ch == "}":
            depth -= 1
        if ch == "&" and depth == 0:
            cells.append(cell)
            cell = ""
        else:
            cell += ch
        k += 1
    if cell.strip() or cells:
        cells.append(cell)
        rows.append(cells)
    return [r for r in rows if any(c.strip() for c in r) or len(r) > 1]


def structure_check(body, expect_cols):
    """Each row must have the same number of & -separated cells (tblr counts
    spanned positions as empty cells)."""
    rows = split_rows(strip_comments(body))
    widths = [len(r) for r in rows]
    if not widths:
        return
    cols = expect_cols or max(set(widths), key=widths.count)
    bad = [(i + 1, w) for i, w in enumerate(widths) if w != cols]
    print(f"rows   {len(rows)} rows, {cols} columns")
    for i, w in bad[:10]:
        print(f"WARNING: row {i} has {w} cells, expected {cols} "
              "(spanned positions still need an empty cell: '\\SetCell[c=2]{c} x & &')")


def norm(s):
    s = unicodedata.normalize("NFKC", s)
    s = s.replace("\u2212", "-").replace(",", "")
    return re.sub(r"\s+", "", s)


def content_check(cells_path, pdf):
    data = json.loads(read_text(cells_path))
    out = norm(run(["pdftotext", "-layout", pdf, "-"]).stdout)
    missing = []
    for i, row in enumerate(data["cells"]):
        for j, c in enumerate(row):
            if c and c["text"].strip() and norm(c["text"]) not in out:
                missing.append((i + 1, j + 1, c["text"]))
    n = sum(1 for row in data["cells"] for c in row if c and c["text"].strip())
    print(f"cells  {n - len(missing)}/{n} source cells found in the output ({os.path.basename(cells_path)})")
    for i, j, t in missing[:15]:
        print(f"  missing r{i} c{j}: {t!r}")
    if missing:
        print("WARNING: cells differ from the source. Fine only if the user asked for it "
              "(then note it in TAB.request.md) or the text is typeset differently on purpose")
    return data["cols"]


def overlay(ref, render, chk, name):
    """Fit both ink boxes onto each other: the table's own rules and text then
    line up whatever margins the source image had."""
    tref = os.path.join(chk, "_ref-trim.png")
    tren = os.path.join(chk, "_ren-trim.png")
    run(["magick", ref + "[0]", "-background", "white", "-alpha", "remove", "-colorspace", "Gray",
         "-fuzz", "8%", "-trim", "+repage", tref])
    rw, rh = map(int, run(["magick", "identify", "-format", "%w %h", tref]).stdout.split())
    run(["magick", render, "-background", "white", "-alpha", "remove", "-colorspace", "Gray",
         "-fuzz", "8%", "-trim", "+repage", "-resize", f"{rw}x{rh}!", tren])
    ov = os.path.join(chk, name + "-overlay.png")
    run(["magick", "(", tref, "+level-colors", "rgb(225,30,30),white", ")",
         "(", tren, "+level-colors", "rgb(20,60,230),white", ")",
         "-compose", "Multiply", "-composite", ov])
    cmp_ = os.path.join(chk, name + "-compare.png")
    h = 700
    run(["magick",
         "(", tref, "-resize", f"x{h}", "-gravity", "North", "-splice", "0x34", "-pointsize", "24",
         "-annotate", "+0+4", "source", ")",
         "(", tren, "-resize", f"x{h}", "-gravity", "North", "-splice", "0x34", "-pointsize", "24",
         "-annotate", "+0+4", "tblr", ")",
         "-bordercolor", "gray70", "-border", "2", "-append" if rw > 1.6 * rh else "+append", cmp_])
    os.remove(tref)
    os.remove(tren)
    print(f"check  {ov}\n       {cmp_}")
    print("       overlay: red = only in source, blue = only in tblr, dark = matches. "
          "Differences the user asked for are expected -- list them in TAB.request.md")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0],
                                 formatter_class=argparse.RawDescriptionHelpFormatter,
                                 epilog=__doc__.split("Usage", 1)[1])
    ap.add_argument("tab")
    ap.add_argument("--preamble")
    ap.add_argument("--engine", default="auto", choices=["auto", "lualatex", "pdflatex", "xelatex"])
    ap.add_argument("--ref")
    ap.add_argument("--dpi", type=int, default=220)
    ap.add_argument("--caption", default="")
    ap.add_argument("--label")
    ap.add_argument("--outdir")
    ap.add_argument("--doc")
    ap.add_argument("--textwidth-cm", type=float)
    a = ap.parse_args()

    engine = "lualatex" if a.engine == "auto" else a.engine
    need(engine, "pdftoppm", "pdftotext")
    tab = os.path.abspath(a.tab)
    if not os.path.isfile(tab):
        sys.exit(f"error: {a.tab} not found")
    name = os.path.splitext(os.path.basename(tab))[0]
    check_name(name, "table name")
    if a.ref:
        if not os.path.isfile(a.ref):
            sys.exit(f"error: reference image {a.ref} not found")
        check_path(a.ref, "--ref")
        need("magick")
    src_dir = os.path.dirname(tab)
    outdir = os.path.abspath(a.outdir or src_dir)
    pre_path = a.preamble or os.path.join(src_dir, name + ".preamble.tex")
    if a.preamble and not os.path.isfile(a.preamble):
        sys.exit(f"error: --preamble {a.preamble} not found")

    manifest = os.path.join(outdir, "_build", "generated.txt")
    ours = set(read_text(manifest).split("\n")) if os.path.exists(manifest) else set()
    products = [name + e for e in (".pdf", ".png", ".svg", ".standalone.tex", ".snippet.tex")]
    copies = []
    if src_dir != outdir:
        copies.append((tab, name + ".tblr"))
        if os.path.exists(pre_path):
            copies.append((pre_path, name + ".preamble.tex"))
    sa_path = os.path.join(outdir, name + ".standalone.tex")
    if os.path.exists(sa_path) and read_text(sa_path).startswith(MARK):
        ours |= set(products)
    clash = [p for p in products + [d for _, d in copies]
             if os.path.exists(os.path.join(outdir, p)) and p not in ours]
    if clash:
        sys.exit("error: refusing to overwrite %s in %s (not generated by build.py). "
                 "Rename the .tblr or pass another --outdir." % (", ".join(clash), outdir))
    os.makedirs(os.path.join(outdir, "_build"), exist_ok=True)
    write_text(manifest, "\n".join(sorted((ours | set(products) | {d for _, d in copies}) - {""})))
    for s, d in copies:
        shutil.copy(s, os.path.join(outdir, d))

    preamble = []
    if os.path.exists(pre_path):
        ptext = read_text(pre_path)
        check_source(pre_path, ptext)
        preamble = [l.rstrip() for l in ptext.splitlines() if l.strip()]
    if not any(re.search(r"\\usepackage\s*(\[[^\]]*\])?\s*\{[^}]*\btabularray\b", strip_comments(l))
               for l in preamble):
        preamble.insert(0, "\\usepackage{tabularray}")
    # bg= / fg= need xcolor, which tabularray does not load by itself
    if re.search(r"\b(bg|fg)\s*=", strip_comments(read_text(tab))) and not any(
            re.search(r"\{[^}]*\bxcolor\b", l) for l in preamble):
        preamble.append("\\usepackage{xcolor}")
        print("note   added \\usepackage{xcolor} (the table uses bg= / fg=); put it in TAB.preamble.tex")
    # \UseTblrLibrary must come after \usepackage{tabularray}
    preamble.sort(key=lambda l: 1 if "\\UseTblrLibrary" in l else 0)

    body = read_text(tab)
    check_source(tab, body)
    code = strip_comments(body)
    if "\\documentclass" in code or "\\begin{document}" in code:
        sys.exit("error: TAB.tblr must contain only the table environment, not a full document")
    env = ENV.search(code)
    if not env:
        sys.exit("error: no \\begin{tblr} / {longtblr} / {talltblr} in " + a.tab)
    long_table = env.group(1) == "longtblr"
    cjk = bool(CJK.search(body))
    if cjk and engine == "pdflatex":
        print("WARNING: Japanese text with pdflatex -- the host document needs CJK support")

    sa = name + ".standalone.tex"
    write_text(os.path.join(outdir, sa), doc(preamble, "\\input{%s.tblr}\\unskip" % name, engine, cjk, long_table))
    ok, pdf, log = compile_tex(engine, sa, outdir)
    if not ok:
        print("COMPILE FAILED\n" + tex_errors(log))
        sys.exit(1)
    warn = tex_errors(log)
    if warn:
        print(warn)
    shutil.copy(pdf, os.path.join(outdir, name + ".pdf"))
    if long_table:   # crop the tall page to the table
        run(["pdftoppm", "-png", "-r", str(a.dpi), "-f", "1", "-l", "1", "-singlefile", pdf,
             os.path.join(outdir, name)])
        run(["magick", os.path.join(outdir, name + ".png"), "-trim", "+repage", "-bordercolor", "white",
             "-border", "20", os.path.join(outdir, name + ".png")])
    else:
        run(["pdftoppm", "-png", "-r", str(a.dpi), "-singlefile", pdf, os.path.join(outdir, name)])
    svg = os.path.join(outdir, name + ".svg")
    if os.path.exists(svg):
        os.remove(svg)
    if not (shutil.which("pdftocairo") and run(["pdftocairo", "-svg", pdf, svg], check=False).returncode == 0):
        print("WARNING: SVG not written (pdftocairo missing or failed)")
    size = None if long_table else pdf_size_cm(pdf)
    if size:
        w = size[0] - 0.21
        print(f"built  {outdir}/{name}.pdf  ({w:.2f} x {size[1] - 0.21:.2f} cm)")
        if a.textwidth_cm and w > a.textwidth_cm:
            print(f"WARNING: wider than the text width {a.textwidth_cm} cm -- give the table "
                  "width=\\linewidth with X columns, or shrink the font (references/tabularray.md)")
    else:
        print(f"built  {outdir}/{name}.pdf" + ("  (longtblr: page-sized build)" if long_table else ""))

    # checks: structure, content against the source, the user's requests
    cells_path = os.path.join(src_dir, name + ".cells.json")
    cols = content_check(cells_path, pdf) if os.path.exists(cells_path) else None
    structure_check(body, cols)
    report_requests(os.path.join(src_dir, name + ".request.md"))

    label = a.label or "tab:" + name
    snippet = ["% --- preamble (once per document) ---"] + ["% " + l for l in preamble]
    if cjk:
        snippet.append("% (contains Japanese: host document must be (u)pLaTeX / LuaLaTeX-ja / XeCJK)")
    base = os.path.dirname(os.path.abspath(a.doc)) if a.doc else os.getcwd()
    rel = posix_rel(os.path.join(outdir, name + ".tblr"), base)
    snippet.append("% --- body (\\input path relative to " + (a.doc or "the current directory") + ") ---")
    if long_table:
        snippet += ["% longtblr carries its own caption: \\begin{longtblr}[caption={...},label={%s}]" % label,
                    "\\input{%s}" % rel, ""]
    else:
        snippet += ["\\begin{table}[htbp]", "  \\centering", "  \\caption{%s}" % a.caption,
                    "  \\label{%s}" % label, "  \\input{%s}" % rel, "\\end{table}", ""]
    write_text(os.path.join(outdir, name + ".snippet.tex"), "\n".join(snippet))

    if a.ref:
        chk = os.path.join(outdir, "_check")
        os.makedirs(chk, exist_ok=True)
        overlay(os.path.abspath(a.ref), os.path.join(outdir, name + ".png"), chk, name)
    print(f"snippet {outdir}/{name}.snippet.tex")


if __name__ == "__main__":
    main()

SHA-256: b0b115e54d327f08e2d167fb4361bde25cc01868a36dc818e35f51c639e9ff28