changh95's picture
tt-model push paddleocr-vl (container)
22e0325 verified
Raw History Blame Contribute Delete
6.94 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Minimal client of the PaddleOCR-VL server (standard library only; Python 3.9+).
python3 client.py crop.png # task ocr via /ocr
python3 client.py table.png --task table --html # the table as HTML
python3 client.py page.png --task spotting --json # the whole answer (boxes in result.items)
python3 client.py crop.png --chat --stream # OpenAI chat completions, streamed
python3 client.py crop.png --prompt "Formula Recognition:" --temperature 0.7 --seed 1
Functions: :func:`ocr`, :func:`ocr_stream`, :func:`chat`, :func:`chat_stream`, :func:`get`.
"""
from __future__ import annotations
import argparse
import base64
import json
import sys
import urllib.error
import urllib.request
from typing import Any, Dict, Iterator, Optional, Tuple
def _post(url: str, body: Dict[str, Any], timeout: float = 600.0):
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST")
return urllib.request.urlopen(req, timeout=timeout)
def get(url: str, timeout: float = 30.0) -> Tuple[Optional[int], Any]:
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
try:
return e.code, json.loads(e.read())
except ValueError:
return e.code, None
except Exception: # noqa: BLE001
return None, None
def _call(url: str, body: Dict[str, Any], timeout: float) -> Tuple[int, Any, float]:
import time
t0 = time.time()
try:
with _post(url, body, timeout) as r:
return r.status, json.loads(r.read()), (time.time() - t0) * 1e3
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw), (time.time() - t0) * 1e3
except ValueError:
return e.code, raw.decode(errors="replace"), (time.time() - t0) * 1e3
def _events(resp) -> Iterator[Dict[str, Any]]:
for raw in resp:
line = raw.decode("utf-8").strip()
if not line.startswith("data: "):
continue
if line == "data: [DONE]":
return
yield json.loads(line[6:])
def ocr(base: str, image: bytes, timeout: float = 600.0, **params) -> Tuple[int, Any, float]:
"""POST /ocr -> (status, body, client ms). params: task, prompt, max_new_tokens, temperature, top_k, top_p,
repetition_penalty, seed, max_pixels, min_pixels, skip_special_tokens, return_tokens."""
body = {"image": base64.b64encode(image).decode()}
body.update({k: v for k, v in params.items() if v is not None})
return _call(base.rstrip("/") + "/ocr", body, timeout)
def ocr_stream(base: str, image: bytes, timeout: float = 600.0, **params) -> Iterator[Dict[str, Any]]:
body = {"image": base64.b64encode(image).decode(), "stream": True}
body.update({k: v for k, v in params.items() if v is not None})
with _post(base.rstrip("/") + "/ocr", body, timeout) as r:
yield from _events(r)
def chat_body(image: bytes, text: str = "OCR:", mime: str = "image/png", **params) -> Dict[str, Any]:
url = f"data:{mime};base64," + base64.b64encode(image).decode()
body = {"model": "paddleocr-vl", "messages": [{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": url}}, {"type": "text", "text": text}]}]}
body.update({k: v for k, v in params.items() if v is not None})
return body
def chat(base: str, image: bytes, text: str = "OCR:", timeout: float = 600.0, **params) -> Tuple[int, Any, float]:
"""POST /v1/chat/completions (non-streamed) -> (status, body, client ms)."""
return _call(base.rstrip("/") + "/v1/chat/completions", chat_body(image, text, **params), timeout)
def chat_stream(base: str, image: bytes, text: str = "OCR:", timeout: float = 600.0,
**params) -> Iterator[Dict[str, Any]]:
body = chat_body(image, text, stream=True, **params)
with _post(base.rstrip("/") + "/v1/chat/completions", body, timeout) as r:
yield from _events(r)
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", default=None)
ap.add_argument("--prompt", default=None)
ap.add_argument("--max-new-tokens", type=int, default=None)
ap.add_argument("--temperature", type=float, default=None)
ap.add_argument("--top-k", type=int, default=None)
ap.add_argument("--top-p", type=float, default=None)
ap.add_argument("--repetition-penalty", type=float, default=None)
ap.add_argument("--seed", type=int, default=None)
ap.add_argument("--max-pixels", type=int, default=None)
ap.add_argument("--chat", action="store_true", help="use /v1/chat/completions")
ap.add_argument("--stream", action="store_true")
ap.add_argument("--html", action="store_true", help="print the table HTML (task table)")
ap.add_argument("--json", action="store_true", help="print the whole JSON answer")
a = ap.parse_args()
img = open(a.image, "rb").read()
p = dict(task=a.task, prompt=a.prompt, max_new_tokens=a.max_new_tokens, temperature=a.temperature,
top_k=a.top_k, top_p=a.top_p, repetition_penalty=a.repetition_penalty, seed=a.seed,
max_pixels=a.max_pixels)
if a.chat:
text = a.prompt or a.task or "OCR:"
extra = {k: v for k, v in p.items() if k not in ("task", "prompt", "max_new_tokens")}
extra["max_tokens"] = a.max_new_tokens
if a.stream:
for ev in chat_stream(a.url, img, text, **extra):
for ch in ev.get("choices") or []:
sys.stdout.write(ch.get("delta", {}).get("content") or "")
sys.stdout.flush()
print()
return 0
st, body, ms = chat(a.url, img, text, **extra)
print(json.dumps(body, ensure_ascii=False, indent=1) if a.json or st != 200
else body["choices"][0]["message"]["content"])
return 0 if st == 200 else 1
if a.stream:
for ev in ocr_stream(a.url, img, **p):
if ev.get("type") == "delta":
sys.stdout.write(ev["delta"])
sys.stdout.flush()
elif ev.get("type") == "error":
print(f"\nerror: {ev}")
return 1
print()
return 0
st, body, ms = ocr(a.url, img, **p)
if st != 200 or a.json:
print(json.dumps(body, ensure_ascii=False, indent=1))
elif a.html and "html" in (body.get("result") or {}):
print(body["result"]["html"])
else:
print(body["text"])
return 0 if st == 200 else 1
if __name__ == "__main__":
sys.exit(main())