"""PP-StructureV3 on a scanned PDF: book.md plus one JSON file per page
(brasspage.com/pp-structure/, Nov 15, 2026)."""

import argparse
from pathlib import Path

from paddleocr import PPStructureV3

ap = argparse.ArgumentParser()
ap.add_argument("pdf")
ap.add_argument("--out", default="out")
ap.add_argument("--threads", type=int, default=10)  # PaddleOCR's default
# --flat: no page turn, unwarp or line turn models
ap.add_argument("--flat", action="store_true")
# --mobile: the small PP-OCRv5 mobile OCR models, not server
ap.add_argument("--mobile", action="store_true")
# --light: --flat --mobile, and no table, formula or region models
ap.add_argument("--light", action="store_true")
a = ap.parse_args()

opts = {"cpu_threads": a.threads}
if a.flat or a.light:
    opts["use_doc_orientation_classify"] = False
    opts["use_doc_unwarping"] = False
    opts["use_textline_orientation"] = False
if a.mobile or a.light:
    opts["text_detection_model_name"] = "PP-OCRv5_mobile_det"
    opts["text_recognition_model_name"] = "PP-OCRv5_mobile_rec"
if a.light:
    opts["use_table_recognition"] = False
    opts["use_formula_recognition"] = False
    opts["use_region_detection"] = False
pipe = PPStructureV3(**opts)
out = Path(a.out)
out.mkdir(exist_ok=True)
pages = list(pipe.predict(a.pdf))
for res in pages:
    res.save_to_json(str(out))  # out/<name>_<page>_res.json: blocks, boxes, text
md = pipe.concatenate_markdown_pages([r.markdown for r in pages])
# md is a MarkdownResult, not a str: write its text
(out / "book.md").write_text(md["markdown_texts"])
