"""Read a whole Vietnamese page with VietOCR. MIT license, Brasspage (https://brasspage.com/vietocr/), Nov 2026.

VietOCR reads one cropped text line and finds no lines itself. This script asks Tesseract where the lines are,
cuts each line at word gaps into pieces no wider than SPAN times the line height (VietOCR squeezes a crop wider
than 16:1 into 512 x 32 pixels), reads each piece with VietOCR and prints the page in Tesseract's line order,
a blank line between paragraphs.

  pip install vietocr torch torchvision "setuptools<81"   # tested on Python 3.12
  python vietocr_page.py page.jpg [more.jpg ...] [--model vgg_seq2seq]

It also needs Tesseract 5 with vie on the PATH. Every run fetches the model config from the VietOCR author's server
(vocr.vn), and the first run also downloads the weights from there. VietOCR's own messages go to stderr, so stdout
holds only the page text. If a weights download stops, delete the part file (vgg_transformer.pth or vgg_seq2seq.pth
in your temp folder): VietOCR uses any file it finds there.
"""

import argparse
import contextlib
import subprocess
import sys

from PIL import Image

PAD = 0.15  # crop margin, a share of the line height on each side
SPAN = 16  # longest piece, in line heights: VietOCR's 512 x 32 input


def lines(tsv):
    """[(paragraph key, line height, [(left, top, width, height) of each word])] in Tesseract's order."""
    out, height = {}, {}
    for row in tsv.splitlines()[1:]:
        c = row.split("\t")
        if len(c) < 12:
            continue
        key = tuple(map(int, c[1:5]))  # page, block, paragraph, line
        box = tuple(map(int, c[6:10]))
        if c[0] == "4":
            height[key] = box[3]
        elif c[0] == "5" and c[11].strip():
            out.setdefault(key, []).append(box)
    return [(k[:3], height.get(k, max(b[3] for b in ws)), ws) for k, ws in out.items()]


def pieces(words, h, span=SPAN):
    """Split one line's words, left to right, into runs no wider than span x h (a single long word stays whole)."""
    runs = []
    for b in sorted(words):
        if runs and b[0] + b[2] - runs[-1][0][0] <= span * h:
            runs[-1].append(b)
        else:
            runs.append([b])
    return [
        (
            r[0][0],
            min(b[1] for b in r),
            max(b[0] + b[2] for b in r),
            max(b[1] + b[3] for b in r),
        )
        for r in runs
    ]


def crops(img, ls, span=SPAN, pad=PAD):
    """[(line index, cropped piece)] for every piece of every line."""
    W, H = img.size
    out = []
    for i, (_, h, ws) in enumerate(ls):
        p = round(pad * h)
        for x0, y0, x1, y1 in pieces(ws, h, span):
            out.append(
                (
                    i,
                    img.crop(
                        (max(0, x0 - p), max(0, y0 - p), min(W, x1 + p), min(H, y1 + p))
                    ),
                )
            )
    return out


def text(ls, cut, got):
    """Join the pieces back into lines and the lines into paragraphs."""
    row = [[] for _ in ls]
    for (i, _), s in zip(cut, got):
        row[i].append(s)
    out, last = [], None
    for (par, _, _), r in zip(ls, row):
        if last is not None and par != last:
            out.append("")
        out.append(" ".join(r))
        last = par
    return "\n".join(out) + "\n"


def read(path, pred, lang="vie", span=SPAN, pad=PAD):
    tsv = subprocess.run(
        [
            "tesseract",
            str(path),
            "-",
            "-l",
            lang,
            "-c",
            "tessedit_create_tsv=1",
            "-c",
            "tessedit_create_txt=0",
        ],
        capture_output=True,
        text=True,
        check=True,
    ).stdout
    ls = lines(tsv)
    cut = crops(Image.open(path).convert("RGB"), ls, span, pad)
    got = pred.predict_batch([c for _, c in cut]) if cut else []
    return text(ls, cut, got)


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("images", nargs="+")
    ap.add_argument(
        "--model", default="vgg_transformer", choices=("vgg_transformer", "vgg_seq2seq")
    )
    a = ap.parse_args()
    from vietocr.tool.config import Cfg
    from vietocr.tool.predictor import Predictor

    with contextlib.redirect_stdout(sys.stderr):  # VietOCR prints download notes
        cfg = Cfg.load_config_from_name(a.model)
        cfg["device"] = "cpu"
        cfg["cnn"]["pretrained"] = False
        pred = Predictor(cfg)
    for p in a.images:
        print(read(p, pred), end="")


if __name__ == "__main__":
    main()
