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

    python examples/quickstart.py page.png [http://localhost:20000] [markdown|free] [gundam|base|small]

It sends the image to the OpenAI-compatible route as a data URL with the task's official prompt (the two prompts of
the DeepSeek-OCR-2 model card) and streams the model's output as it is decoded (grounding tags included; POST /ocr
returns the cleaned Markdown and the boxes)."""
import base64
import json
import sys
import urllib.request

PROMPTS = {"markdown": "<image>\n<|grounding|>Convert the document to markdown.", "free": "<image>\nFree OCR."}
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 "markdown"
mode = sys.argv[4] if len(sys.argv) > 4 else None          # gundam (the default) | base | small
data = open(path, "rb").read()
mime = "image/png" if data.startswith(b"\x89PNG") else "image/jpeg"
image = f"data:{mime};base64," + base64.b64encode(data).decode()
body = {"model": "deepseek-ocr-2", "stream": True, "stream_options": {"include_usage": True},
        "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": image}},
                                                  {"type": "text", "text": PROMPTS[task]}]}]}
if mode:
    body["mode"] = mode
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()