#!/usr/bin/env python3
"""
Workshop Document: read an uploaded PDF's pages and word boxes.

Usage: ocr.py <in.pdf>

Prints JSON to stdout:
  {"status": "ok", "pages": [{"page": 1, "kind": "digital"|"flat", "width": .., "height": ..,
                              "words": [{"bbox": [x0, y0, x1, y1], "text": "..", "line": "b.l"}]}]}
or {"status": "error", "message": ".."} with exit code 1.

A page is digital when it draws visible text, flat otherwise (a scan or image). Flat pages are
OCR'd with Tesseract unless they already carry an (invisible) text layer. Boxes are in display
coordinates; see wdlib.py.
"""

import json
import sys

import wdlib


def main():
    if len(sys.argv) != 2:
        raise wdlib.UserError("usage: ocr.py <in.pdf>")

    doc = wdlib.open_pdf(sys.argv[1])
    pages = []
    for page in doc:
        kind = wdlib.page_kind(page)
        pages.append({
            "page": page.number + 1,
            "kind": kind,
            "width": round(page.rect.width, 2),
            "height": round(page.rect.height, 2),
            "words": wdlib.words(page, wdlib.textpage_for(page, kind)),
        })

    print(json.dumps({"status": "ok", "pages": pages}))


if __name__ == "__main__":
    wdlib.run(main)
