"""PDF tables to CSV with Microsoft's Table Transformer (MIT). From brasspage.com/table-transformer/ (MIT).

  pip install torch transformers timm pypdfium2 pdfplumber pillow
  python tatr2csv.py report.pdf [out_dir] [--ocr] [--model microsoft/table-transformer-structure-recognition]

Each page is drawn at 300 dpi. The detection model finds each table, the structure model finds its rows and columns,
and each word goes to the row and the column it overlaps most. Words come from the PDF's text layer, or from Tesseract
with --ocr (a scan with no text layer; needs the tesseract command). Thresholds are the 0.5 of Microsoft's own
inference.py. Writes <out_dir>/<name>-p<page>-t<n>.csv. The 2 models (about 115 MB each) download on the first run.
"""

import csv
import subprocess
import sys
from pathlib import Path

import pdfplumber
import pypdfium2 as pdfium
import torch
from transformers import (
    AutoImageProcessor,
    TableTransformerConfig,
    TableTransformerForObjectDetection,
)

DPI = 300
PAD = 30  # pixels of margin around a found table (0.1 inch at 300 dpi) before the structure model reads it
DETECT = "microsoft/table-transformer-detection"
STRUCTURE = "microsoft/table-transformer-structure-recognition-v1.1-all"


def load(name):
    # The v1.1 config.json has "dilation": null, which transformers 5 rejects ("expected bool"). Null means False.
    cfg = TableTransformerConfig.get_config_dict(name)[0]
    cfg["dilation"] = bool(cfg.get("dilation"))
    model = TableTransformerForObjectDetection.from_pretrained(name, config=TableTransformerConfig.from_dict(cfg))
    return AutoImageProcessor.from_pretrained(name), model.eval()


def boxes(proc_model, image, longest, threshold=0.5):
    """[(label, score, [x0, y0, x1, y1]), ...] in the image's own pixels. The image is scaled so its longest side is
    `longest` (800 to find tables, 1000 for rows and columns, as Microsoft's inference.py does). The v1.1 processor's
    own size setting ({"longest_edge": 800}) fails in transformers 5, so the size is given here."""
    proc, model = proc_model
    size = {"shortest_edge": longest, "longest_edge": longest}
    with torch.no_grad():
        out = model(**proc(images=image, size=size, return_tensors="pt"))
    r = proc.post_process_object_detection(out, threshold=threshold, target_sizes=[image.size[::-1]])[0]
    names = model.config.id2label
    return [(names[int(l)], float(s), [float(v) for v in b]) for l, s, b in zip(r["labels"], r["scores"], r["boxes"])]


def text_words(pdf_page):
    """The text layer's words as (x0, top, x1, bottom, text) in 300 dpi pixels."""
    k = DPI / 72
    return [(w["x0"] * k, w["top"] * k, w["x1"] * k, w["bottom"] * k, w["text"]) for w in pdf_page.extract_words()]


def ocr_words(image):
    """Tesseract's words (TSV output) as (x0, top, x1, bottom, text)."""
    tsv = subprocess.run(
        ["tesseract", "-", "-", "--dpi", str(DPI), "tsv"], input=png(image), capture_output=True, check=True
    ).stdout.decode()
    out = []
    for line in tsv.splitlines()[1:]:
        f = line.split("\t")
        if len(f) == 12 and f[0] == "5" and f[11].strip():
            x, y, w, h = map(int, f[6:10])
            out.append((x, y, x + w, y + h, f[11].strip()))
    return out


def png(image):
    import io

    b = io.BytesIO()
    image.save(b, "PNG")
    return b.getvalue()


def overlap(a0, a1, b0, b1):
    return max(0.0, min(a1, b1) - max(a0, b0))


def table_grid(structure, crop, words):
    """Rows x columns from the structure model; each word (crop pixels) goes to its best row and column."""
    found = boxes(structure, crop, 1000)
    rows = sorted((b for l, s, b in found if l == "table row"), key=lambda b: b[1] + b[3])
    cols = sorted((b for l, s, b in found if l == "table column"), key=lambda b: b[0] + b[2])
    if not rows or not cols:
        return []
    cells = {}
    for x0, y0, x1, y1, t in words:
        r = max(range(len(rows)), key=lambda i: overlap(y0, y1, rows[i][1], rows[i][3]))
        c = max(range(len(cols)), key=lambda j: overlap(x0, x1, cols[j][0], cols[j][2]))
        if overlap(y0, y1, rows[r][1], rows[r][3]) > 0 and overlap(x0, x1, cols[c][0], cols[c][2]) > 0:
            cells.setdefault((r, c), []).append((y0, y1, x0, t))
    grid = [[join(cells.get((r, c), [])) for c in range(len(cols))] for r in range(len(rows))]
    grid = [row for row in grid if any(row)]
    keep = [c for c in range(len(cols)) if any(row[c] for row in grid)]
    return [[row[c] for c in keep] for row in grid]


def join(ws):
    """A cell's words in reading order: lines top to bottom (a new line starts below half a word's height)."""
    lines = []
    for y0, y1, x0, t in sorted(ws):
        if lines and y0 < lines[-1][0] + (y1 - y0) / 2:
            lines[-1][1].append((x0, t))
        else:
            lines.append([y0, [(x0, t)]])
    return " ".join(t for _, line in lines for _, t in sorted(line))


def convert(pdf, out_dir, ocr=False, detect=None, structure=None):
    """Writes one CSV a table; returns the list of tables (each a list of rows)."""
    detect, structure = detect or load(DETECT), structure or load(STRUCTURE)
    out_dir.mkdir(parents=True, exist_ok=True)
    tables = []
    with pdfplumber.open(pdf) as plumb:
        doc = pdfium.PdfDocument(str(pdf))
        for p in range(len(doc)):
            image = doc[p].render(scale=DPI / 72).to_pil().convert("RGB")
            words = ocr_words(image) if ocr else text_words(plumb.pages[p])
            found = [b for l, s, b in boxes(detect, image, 800) if l in ("table", "table rotated")]
            for n, (x0, y0, x1, y1) in enumerate(sorted(found, key=lambda b: (b[1], b[0])), 1):
                x0, y0 = max(0, x0 - PAD), max(0, y0 - PAD)
                x1, y1 = min(image.width, x1 + PAD), min(image.height, y1 + PAD)
                inside = [(a - x0, b - y0, c - x0, d - y0, t) for a, b, c, d, t in words
                          if x0 <= (a + c) / 2 <= x1 and y0 <= (b + d) / 2 <= y1]
                grid = table_grid(structure, image.crop((x0, y0, x1, y1)), inside)
                if grid:
                    tables.append(grid)
                    with (out_dir / f"{pdf.stem}-p{p + 1}-t{n}.csv").open("w", newline="", encoding="utf-8") as f:
                        csv.writer(f).writerows(grid)
        doc.close()
    return tables


if __name__ == "__main__":
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    if not args:
        sys.exit(__doc__)
    model = sys.argv[sys.argv.index("--model") + 1] if "--model" in sys.argv else STRUCTURE
    args = [a for a in args if a != model]
    pdf = Path(args[0])
    out = Path(args[1]) if len(args) > 1 else pdf.parent
    tables = convert(pdf, out, ocr="--ocr" in sys.argv, structure=load(model))
    print(f"{len(tables)} tables from {pdf.name} -> {out}")
