File size: 1,588 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""OCR an image with a running GLM-OCR server (tt serve changh95/GLM-OCR), standard library only:

    python examples/quickstart.py page.png [http://localhost:20000] [text|table|formula]

It sends the image to the OpenAI-compatible route as a data URL and streams the text as it is decoded."""
import base64
import json
import sys
import urllib.request

path = sys.argv[1]
url = (sys.argv[2] if len(sys.argv) > 2 else "http://localhost:20000").rstrip("/") + "/v1/chat/completions"
task = sys.argv[3] if len(sys.argv) > 3 else "text"
prompt = {"text": "Text Recognition:", "table": "Table Recognition:", "formula": "Formula Recognition:"}[task]
image = "data:image/png;base64," + base64.b64encode(open(path, "rb").read()).decode()
body = {"model": "glm-ocr", "stream": True, "stream_options": {"include_usage": True},
        "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": image}},
                                                  {"type": "text", "text": prompt}]}]}
req = urllib.request.Request(url, 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()