# SPDX-License-Identifier: Apache-2.0 """Parse a document with a running Unlimited-OCR-2 server (tt serve changh95/Unlimited-OCR-2), standard library only: python examples/quickstart.py page1.png [page2.png ...] [--url http://localhost:20000] [--mode gundam|base] [--json] All pages go in ONE request, in order (one image_url part each) through the OpenAI-compatible route, with the official instruction (the server writes "" per page in front of it); the model's output is streamed as it is decoded (page and block tags included: label[x1, y1, x2, y2]content). With --json the pages go to POST /ocr instead and the parsed pages / blocks (boxes in pixels of each page) are printed.""" import argparse import base64 import json import sys import urllib.request ap = argparse.ArgumentParser() ap.add_argument("pages", nargs="+") ap.add_argument("--url", default="http://localhost:20000") ap.add_argument("--mode", choices=("gundam", "base"), help="default: gundam for one page, base for several") ap.add_argument("--json", action="store_true", help="POST /ocr format=json: the parsed pages and blocks") args = ap.parse_args() url = args.url.rstrip("/") def data_url(path): data = open(path, "rb").read() mime = "image/png" if data.startswith(b"\x89PNG") else "image/jpeg" return f"data:{mime};base64," + base64.b64encode(data).decode() if args.json: body = {"images": [data_url(p) for p in args.pages], "format": "json"} if args.mode: body["mode"] = args.mode req = urllib.request.Request(url + "/ocr", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) res = json.load(urllib.request.urlopen(req)) for page in res["json"]["pages"]: print(f"--- page {page['page']} ({page['width']} x {page['height']})") for b in page["blocks"]: print(f"{b['label']} {b['box']}: {b['text'][:80]!r}") print(res["usage"], res["finish_reason"], file=sys.stderr) sys.exit(0) content = [{"type": "image_url", "image_url": {"url": data_url(p)}} for p in args.pages] content.append({"type": "text", "text": "Multi page parsing."}) body = {"model": "unlimited-ocr-2", "stream": True, "stream_options": {"include_usage": True}, "messages": [{"role": "user", "content": content}]} if args.mode: body["mode"] = args.mode req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req) as r: for line in r: line = line.decode().strip() if not line.startswith("data: ") or line == "data: [DONE]": continue chunk = json.loads(line[6:]) for choice in chunk["choices"]: print(choice["delta"].get("content", ""), end="", flush=True) if chunk.get("usage"): print("\n", chunk["usage"], file=sys.stderr) print()