"""MiniCPM-OCR 1.0 on whole pages via llama-server: python3 ocr_page.py *.jpg > book.txt"""

import base64
import json
import sys
import urllib.request

URL = "http://127.0.0.1:18499/v1/chat/completions"


def ask(path):
    with open(path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode()
    body = {
        "model": "minicpm-ocr",
        "temperature": 0,
        "top_k": 1,
        "max_tokens": 4096,
        "messages": [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
                    {"type": "text", "text": "Text Recognition:"},
                ],
            }
        ],
    }
    req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=600) as r:
        return json.load(r)


if __name__ == "__main__":
    for p in sys.argv[1:]:
        print(ask(p)["choices"][0]["message"]["content"])
