#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Minimal client of the GLM-OCR server (standard library only; Python 3.9+). python3 client.py page.png [--url http://127.0.0.1:20000] [--task text|table|formula|extract] [--schema '{"name": ""}'] [--prompt TEXT] [--format raw|markdown|json] [--stream] [--chat] As a module: ``ocr(url, image_bytes, **fields)`` (multipart ``POST /ocr``), ``ocr_json(url, image_bytes, **fields)`` (JSON body), ``ocr_stream(url, image_bytes, **fields)`` (yields the SSE events), ``chat(url, image_bytes, text, **params)`` / ``chat_stream(...)`` (``POST /v1/chat/completions`` with a data URL), ``get(url, path)``. """ from __future__ import annotations import argparse import base64 import json import sys import urllib.error import urllib.request import uuid from typing import Any, Dict, Iterator, Optional, Tuple MIME = {b"\x89PNG": "image/png", b"\xff\xd8\xff": "image/jpeg", b"RIFF": "image/webp", b"GIF8": "image/gif", b"BM": "image/bmp", b"II*\x00": "image/tiff", b"MM\x00*": "image/tiff"} def mime_of(data: bytes) -> str: for magic, m in MIME.items(): if data.startswith(magic): return m return "application/octet-stream" def data_url(data: bytes) -> str: return f"data:{mime_of(data)};base64," + base64.b64encode(data).decode("ascii") def multipart(fields: Dict[str, Any], file_bytes: bytes, filename: str = "image") -> Tuple[bytes, str]: b = "----glmocr" + uuid.uuid4().hex out = [] for k, v in fields.items(): if v is None: continue if isinstance(v, (dict, list)): v = json.dumps(v, ensure_ascii=False) out.append(f"--{b}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n".encode("utf-8")) out.append(f"--{b}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\n" f"Content-Type: {mime_of(file_bytes)}\r\n\r\n".encode() + file_bytes + b"\r\n") out.append(f"--{b}--\r\n".encode()) return b"".join(out), f"multipart/form-data; boundary={b}" def _request(url: str, body: Optional[bytes], ctype: Optional[str], timeout: float): headers = {"Content-Type": ctype} if ctype else {} req = urllib.request.Request(url, data=body, headers=headers, method="POST" if body is not None else "GET") return urllib.request.urlopen(req, timeout=timeout) def _call(url: str, body: Optional[bytes], ctype: Optional[str], timeout: float) -> Tuple[int, Any, Dict[str, str]]: try: r = _request(url, body, ctype, timeout) status, data, hdr = r.status, r.read(), dict(r.headers) except urllib.error.HTTPError as e: status, data, hdr = e.code, e.read(), dict(e.headers) text = data.decode("utf-8", errors="replace") try: return status, json.loads(text), hdr except ValueError: return status, text, hdr def get(url: str, path: str, timeout: float = 30.0) -> Tuple[Optional[int], Any]: try: st, body, _ = _call(url.rstrip("/") + path, None, None, timeout) return st, body except Exception: # noqa: BLE001 -- server not up return None, None def ocr(url: str, image: bytes, timeout: float = 900.0, **fields) -> Tuple[int, Any, Dict[str, str]]: """POST /ocr (multipart) -> (status, JSON or text, headers).""" body, ctype = multipart(fields, image) return _call(url.rstrip("/") + "/ocr", body, ctype, timeout) def ocr_json(url: str, image: bytes, timeout: float = 900.0, **fields) -> Tuple[int, Any, Dict[str, str]]: """POST /ocr with a JSON body (the image as a data URL).""" body = json.dumps(dict(fields, image=data_url(image)), ensure_ascii=False).encode("utf-8") return _call(url.rstrip("/") + "/ocr", body, "application/json", timeout) def _sse(r) -> Iterator[Dict[str, Any]]: for raw in r: line = raw.decode("utf-8").strip() if not line.startswith("data: "): continue if line == "data: [DONE]": return yield json.loads(line[6:]) def ocr_stream(url: str, image: bytes, timeout: float = 900.0, **fields) -> Iterator[Dict[str, Any]]: """The SSE events of POST /ocr with stream=true: {"type": "delta", "text"} ..., then {"type": "done", ...}.""" body, ctype = multipart(dict(fields, stream="true"), image) yield from _sse(_request(url.rstrip("/") + "/ocr", body, ctype, timeout)) def chat_body(image: Optional[bytes], text: str = "", **params) -> Dict[str, Any]: content = [] if image is not None: content.append({"type": "image_url", "image_url": {"url": data_url(image)}}) if text: content.append({"type": "text", "text": text}) return dict({"model": "glm-ocr", "messages": [{"role": "user", "content": content}]}, **params) def chat(url: str, image: Optional[bytes], text: str = "", timeout: float = 900.0, **params) -> Tuple[int, Any, Dict[str, str]]: """POST /v1/chat/completions (non-streaming).""" body = json.dumps(chat_body(image, text, **params), ensure_ascii=False).encode("utf-8") return _call(url.rstrip("/") + "/v1/chat/completions", body, "application/json", timeout) def chat_stream(url: str, image: Optional[bytes], text: str = "", timeout: float = 900.0, **params) -> Iterator[Dict[str, Any]]: """The chat.completion.chunk objects of a streamed chat completion.""" body = json.dumps(chat_body(image, text, stream=True, **params), ensure_ascii=False).encode("utf-8") yield from _sse(_request(url.rstrip("/") + "/v1/chat/completions", body, "application/json", timeout)) def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("image") ap.add_argument("--url", default="http://127.0.0.1:20000") ap.add_argument("--task", choices=("text", "table", "formula", "extract")) ap.add_argument("--prompt") ap.add_argument("--schema", help="extract: a JSON object of the fields to fill") ap.add_argument("--format", choices=("raw", "markdown", "json")) ap.add_argument("--max-new-tokens", type=int) ap.add_argument("--temperature", type=float) ap.add_argument("--max-pixels", type=int) ap.add_argument("--stream", action="store_true") ap.add_argument("--chat", action="store_true", help="use /v1/chat/completions instead of /ocr") args = ap.parse_args() data = open(args.image, "rb").read() if args.chat: params = {k: v for k, v in (("max_tokens", args.max_new_tokens), ("temperature", args.temperature), ("max_pixels", args.max_pixels)) if v is not None} text = args.prompt or "" if args.stream: for c in chat_stream(args.url, data, text, **params): for ch in c.get("choices") or []: print(ch.get("delta", {}).get("content", ""), end="", flush=True) print() return 0 st, body, _ = chat(args.url, data, text, **params) print(body["choices"][0]["message"]["content"] if st == 200 else f"{st} {body}") return 0 if st == 200 else 1 fields = {"task": args.task, "prompt": args.prompt, "schema": args.schema, "format": args.format, "max_new_tokens": args.max_new_tokens, "temperature": args.temperature, "max_pixels": args.max_pixels} if args.stream: for ev in ocr_stream(args.url, data, **fields): if ev.get("type") == "delta": print(ev["text"], end="", flush=True) else: print("\n" + json.dumps({k: v for k, v in ev.items() if k not in ("text", "raw_text")}, ensure_ascii=False)) return 0 st, body, _ = ocr(args.url, data, **fields) if st != 200: print(st, body) return 1 print(body["text"]) print(json.dumps({k: body[k] for k in ("finish_reason", "usage", "image", "timings")}, ensure_ascii=False), file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())