File size: 2,649 Bytes
ca1a504 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | # SPDX-License-Identifier: Apache-2.0
"""Parse a Korean document page with a running schift-ocr-1-beta server (tt serve changh95/schift-ocr-1-beta),
standard library only:
python examples/quickstart.py page.png [--url http://localhost:20000] [--mode gundam|base] [--json]
The page goes through the OpenAI-compatible route with the model card's prompt (<image>document parsing.); the model's
output is streamed as it is decoded (block tags included: <|det|>label [x1, y1, x2, y2]<|/det|>content). With --json
the page goes to POST /ocr instead and the parsed blocks (label, box in pixels, text) are printed."""
import argparse
import base64
import json
import sys
import urllib.request
ap = argparse.ArgumentParser()
ap.add_argument("page")
ap.add_argument("--url", default="http://localhost:20000")
ap.add_argument("--mode", choices=("gundam", "base"), help="default: gundam (the model card's setting)")
ap.add_argument("--json", action="store_true", help="POST /ocr format=json: the parsed blocks")
args = ap.parse_args()
url = args.url.rstrip("/")
data = open(args.page, "rb").read()
mime = "image/png" if data.startswith(b"\x89PNG") else "image/jpeg"
data_url = f"data:{mime};base64," + base64.b64encode(data).decode()
if args.json:
body = {"image": data_url, "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 b in res["json"].get("blocks", []):
print(f"{b['label']} {b['boxes'][0] if b['boxes'] else '-'}: {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}}, {"type": "text", "text": "<image>document parsing."}]
body = {"model": "schift-ocr-1-beta", "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()
|