#!/usr/bin/env python3
"""tag-scan.py: tag the OCR text of an OCRmyPDF file, keep the scan as it looks.

MIT License, Brasspage (https://brasspage.com/image-only-pdf/), 2026.

OCRmyPDF makes a scan searchable, but its output has no tags, so PDF/UA
checkers (veraPDF, PAC) still fail it. This script:
  - tags each OCR text line, and groups lines into paragraphs (P),
  - marks the scan image as a background artifact,
  - sets the title, the language, MarkInfo, DisplayDocTitle and the PDF/UA-1 flag.
It does not check reading order, tables or headings. A person must still check those.

Needs pikepdf (it comes with OCRmyPDF). Made for OCRmyPDF 17 output.
Use:  ocrmypdf scan.pdf ocr.pdf
      python3 tag-scan.py --title "Invoice 1042" --lang en-US ocr.pdf tagged.pdf
"""

import argparse
import itertools
import statistics
import sys

import pikepdf
from pikepdf import Array, Dictionary, Name, Operator


def groups(ops):
    """Split a content stream into top-level items: a state op, or a q..Q / BT..ET group."""
    out, cur, depth = [], None, 0
    for operands, op in ops:
        o = str(op)
        if cur is None and o not in ("q", "BT"):
            out.append(("op", [(operands, op)]))
            continue
        cur = (cur or []) + [(operands, op)]
        depth += 1 if o in ("q", "BT") else -1 if o in ("Q", "ET") else 0
        if depth == 0:
            out.append(("group", cur))
            cur = None
    return out


def line_y(g):
    """Baseline height of one OCR line: the cm move plus the first Td."""
    y = 0.0
    for operands, op in g:
        if str(op) == "cm":
            y += float(operands[5])
        if str(op) == "Td":
            return y + float(operands[1])
    return y


def paragraphs(ys):
    """Start a new paragraph where the gap to the line above is 1.5 times the usual gap, or the text moves up."""
    # ponytail: line-gap rule, fine for letters and forms; columns and tables need real layout analysis
    gaps = [a - b for a, b in itertools.pairwise(ys) if a - b > 0]
    usual = statistics.median(gaps) if gaps else 0
    paras, start = [], 0
    for i in range(1, len(ys)):
        gap = ys[i - 1] - ys[i]
        if gap <= 0 or gap > 1.5 * usual:
            paras.append(list(range(start, i)))
            start = i
    paras.append(list(range(start, len(ys))))
    return paras


def bdc(tag, mcid=None):
    if mcid is None:
        return ([Name("/" + tag)], Operator("BMC"))
    return ([Name("/" + tag), Dictionary(MCID=mcid)], Operator("BDC"))


EMC = ([], Operator("EMC"))

# PDF/A needs the pdfuaid schema declared as an XMP extension schema.
UA_SCHEMA = """<rdf:Description rdf:about="" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/"
 xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#">
<pdfaExtension:schemas><rdf:Bag><rdf:li rdf:parseType="Resource">
<pdfaSchema:namespaceURI>http://www.aiim.org/pdfua/ns/id/</pdfaSchema:namespaceURI>
<pdfaSchema:prefix>pdfuaid</pdfaSchema:prefix><pdfaSchema:schema>PDF/UA identification schema</pdfaSchema:schema>
<pdfaSchema:property><rdf:Seq><rdf:li rdf:parseType="Resource">
<pdfaProperty:name>part</pdfaProperty:name><pdfaProperty:valueType>Integer</pdfaProperty:valueType>
<pdfaProperty:category>internal</pdfaProperty:category><pdfaProperty:description>PDF/UA version</pdfaProperty:description>
</rdf:li></rdf:Seq></pdfaSchema:property></rdf:li></rdf:Bag></pdfaExtension:schemas></rdf:Description>
"""


def tag_page(pdf, page, index, doc):
    xobjs = page.Resources.get("/XObject", {})
    ocr = [k for k in xobjs if k.startswith("/OCR-")]
    if len(ocr) != 1:
        return False
    form = xobjs[ocr[0]]
    lines, out = [], []
    for kind, g in groups(pikepdf.parse_content_stream(form)):
        if kind == "group":
            lines.append(g)
    ys = [line_y(g) for g in lines]
    elems, kids_by_mcid = [], []
    for para in paragraphs(ys):
        p = pdf.make_indirect(
            Dictionary(
                Type=Name.StructElem, S=Name.P, P=doc, Pg=page.obj, K=Array(para)
            )
        )
        elems.append(p)
        kids_by_mcid += [p] * len(para)
    for kind, g in groups(pikepdf.parse_content_stream(page)):
        names = [str(operands[0]) for operands, op in g if str(op) == "Do"]
        if ocr[0] in names:  # inline the OCR form, one marked sequence a line
            out.append(([], Operator("q")))
            for _, s in groups(pikepdf.parse_content_stream(form)):
                if _ == "op":
                    out += s
            for i, g2 in enumerate(lines):
                out += [bdc("P", i), *g2, EMC]
            out.append(([], Operator("Q")))
        else:  # the scan image and anything else: background
            out += [bdc("Artifact"), *g, EMC]
    page.obj.Contents = pdf.make_stream(pikepdf.unparse_content_stream(out))
    fonts = page.Resources.get("/Font", Dictionary())
    for k, v in form.Resources.Font.items():
        fonts[k] = v
    page.Resources.Font = fonts
    del page.Resources.XObject[ocr[0]]
    page.obj.StructParents = index
    page.obj.Tabs = Name.S
    doc.K.extend(elems)
    return kids_by_mcid


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("src")
    ap.add_argument("dst")
    ap.add_argument("--title", help="document title (default: the file's own title)")
    ap.add_argument(
        "--lang", help="language tag, for example en-US (default: keep OCRmyPDF's)"
    )
    a = ap.parse_args()
    pdf = pikepdf.open(a.src)
    if "/StructTreeRoot" in pdf.Root:
        sys.exit("already tagged: " + a.src)
    root = pdf.make_indirect(Dictionary(Type=Name.StructTreeRoot))
    doc = pdf.make_indirect(
        Dictionary(Type=Name.StructElem, S=Name.Document, P=root, K=Array())
    )
    root.K = Array([doc])
    nums, missed = Array(), []
    for i, page in enumerate(pdf.pages):
        kids = tag_page(pdf, page, i, doc)
        if kids is False:
            missed.append(i + 1)
            continue
        nums.extend([i, pdf.make_indirect(Array(kids))])
    root.ParentTree = pdf.make_indirect(Dictionary(Nums=nums))
    root.ParentTreeNextKey = len(pdf.pages)
    pdf.Root.StructTreeRoot = root
    pdf.Root.MarkInfo = Dictionary(Marked=True)
    pdf.Root.ViewerPreferences = Dictionary(DisplayDocTitle=True)
    if a.lang:
        pdf.Root.Lang = a.lang
    title = a.title or str(pdf.docinfo.get("/Title", "")) or a.src
    with pdf.open_metadata(set_pikepdf_as_editor=False) as meta:
        meta["dc:title"] = title
        meta["pdfuaid:part"] = "1"
    xmp = pdf.Root.Metadata.read_bytes().decode()
    if (
        "pdfaid:part" in xmp and "pdfaExtension" not in xmp
    ):  # keep OCRmyPDF's PDF/A claim valid
        pdf.Root.Metadata.write(
            xmp.replace("</rdf:RDF>", UA_SCHEMA + "</rdf:RDF>").encode()
        )
    pdf.save(a.dst)
    if missed:
        sys.exit(f"no OCRmyPDF text layer on page(s) {missed}: run ocrmypdf first")


if __name__ == "__main__":
    main()
