"""PaddleOCR 3.7 on AWS Lambda, one page or a small PDF per call (brasspage.com/paddleocr-lambda/, Nov 26, 2026)."""

import base64
import json
import os
import tempfile

from paddleocr import PaddleOCR

SIZE = os.environ.get("OCR_SIZE", "medium")  # PP-OCRv6 medium, small or tiny
opts = {"cpu_threads": int(os.environ.get("OCR_THREADS", "2"))}  # PaddleOCR's default is 10
if SIZE != "medium":
    opts["text_detection_model_name"] = f"PP-OCRv6_{SIZE}_det"
    opts["text_recognition_model_name"] = f"PP-OCRv6_{SIZE}_rec"
# The text finder sees the page at most 960 px on its long side. 0 = PaddleOCR's default, the page at full
# size (up to 4000 px), which needed 4.5 GB for one 1920 px page and was killed at 3,008 MB.
DET_MAX = int(os.environ.get("OCR_DET_MAX", "960"))
if DET_MAX:
    opts["text_det_limit_type"] = "max"
    opts["text_det_limit_side_len"] = DET_MAX
# Loaded once per container (the cold start), then reused by every warm call.
ocr = PaddleOCR(
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
    use_textline_orientation=False,
    **opts,
)


def handler(event, context):
    body = event.get("body") or ""
    data = base64.b64decode(body) if event.get("isBase64Encoded") else body.encode()
    suffix = ".pdf" if data[:4] == b"%PDF" else ".png"
    with tempfile.NamedTemporaryFile(suffix=suffix, dir="/tmp") as f:
        f.write(data)
        f.flush()
        pages = [r["rec_texts"] for r in ocr.predict(f.name)]
    text = "\n\n".join("\n".join(lines) for lines in pages)
    return {
        "statusCode": 200,
        "headers": {"content-type": "application/json"},
        "body": json.dumps({"pages": len(pages), "text": text}),
    }
