#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # Adapted from this workspace's GLM-OCR bundle (tt_glmocr/server/client.py, Apache-2.0). """Minimal client of the DeepSeek-OCR family's server (standard library only; Python 3.9+). python3 client.py page.png [page2.png ...] [--url http://127.0.0.1:20000] [--task markdown|ocr|free|figure|describe|locate|parse] [--ref TEXT] [--mode tiny|small|base|large|gundam] [--prompt TEXT] [--format raw|markdown|json] [--max-new-tokens N] [--ngram-preset hf|vllm|off|sglang] [--stream] [--chat] Several images are the pages of one request (Unlimited-OCR-2 only; the other models read one image per request). As a module: ``ocr(url, image_bytes, **fields)`` (multipart ``POST /ocr``; ``image_bytes`` may be a list of pages), ``ocr_json(url, image_bytes, **fields)`` (JSON body: ``image``, or ``images`` for a list), ``ocr_stream(url, image_bytes, **fields)`` (yields the SSE events), ``chat(url, image_bytes, text, **params)`` / ``chat_stream(...)`` (``POST /v1/chat/completions`` with data URLs, one ``image_url`` part per image), ``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, List, Optional, Sequence, Tuple, Union 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"} TASKS = ("markdown", "ocr", "free", "figure", "describe", "locate", "parse") MODES = ("tiny", "small", "base", "large", "gundam") Images = Union[bytes, Sequence[bytes]] def _pages(image: Optional[Images]) -> List[bytes]: if image is None: return [] return [image] if isinstance(image, (bytes, bytearray)) else list(image) 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: Images, filename: str = "image") -> Tuple[bytes, str]: """A multipart body: the fields, then one ``file`` part per image (in page order).""" b = "----dsocr" + 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")) pages = _pages(file_bytes) for i, data in enumerate(pages): name = filename if len(pages) == 1 else f"{filename}-{i + 1}" out.append(f"--{b}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{name}\"\r\n" f"Content-Type: {mime_of(data)}\r\n\r\n".encode() + bytes(data) + 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: Images, timeout: float = 1800.0, **fields) -> Tuple[int, Any, Dict[str, str]]: """POST /ocr (multipart; a list of images = the pages) -> (status, JSON or text, headers).""" body, ctype = multipart(fields, image) return _call(url.rstrip("/") + "/ocr", body, ctype, timeout) def ocr_json(url: str, image: Images, timeout: float = 1800.0, **fields) -> Tuple[int, Any, Dict[str, str]]: """POST /ocr with a JSON body (the image as a data URL; a list = ``images``, the pages).""" if isinstance(image, (bytes, bytearray)): fields = dict(fields, image=data_url(bytes(image))) else: fields = dict(fields, images=[data_url(bytes(x)) for x in image]) body = json.dumps(fields, 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: Images, timeout: float = 1800.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[Images], text: str = "", **params) -> Dict[str, Any]: content = [] for data in _pages(image): content.append({"type": "image_url", "image_url": {"url": data_url(bytes(data))}}) if text: content.append({"type": "text", "text": text}) return dict({"model": "deepseek-ocr", "messages": [{"role": "user", "content": content}]}, **params) def chat(url: str, image: Optional[Images], text: str = "", timeout: float = 1800.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[Images], text: str = "", timeout: float = 1800.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", nargs="+", help="the image (several: the pages of one Unlimited-OCR-2 request)") ap.add_argument("--url", default="http://127.0.0.1:20000") ap.add_argument("--task", choices=TASKS) ap.add_argument("--ref", help="locate: the object or text to find") ap.add_argument("--mode", choices=MODES) ap.add_argument("--prompt", help="a free prompt instead of the task's (the image placeholders are added when " "absent)") 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("--ngram-preset", choices=("hf", "vllm", "off", "sglang")) 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() pages = [open(p, "rb").read() for p in args.image] data = pages[0] if len(pages) == 1 else pages if args.chat: params = {k: v for k, v in (("max_tokens", args.max_new_tokens), ("temperature", args.temperature), ("mode", args.mode), ("task", args.task), ("ref", args.ref), ("ngram_preset", args.ngram_preset)) 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, "ref": args.ref, "mode": args.mode, "prompt": args.prompt, "format": args.format, "max_new_tokens": args.max_new_tokens, "temperature": args.temperature, "ngram_preset": args.ngram_preset} 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", "json")}, 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", "mode", "usage", "image", "timings")}, ensure_ascii=False), file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())