File size: 6,937 Bytes
22e0325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/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())