File size: 2,147 Bytes
b8b3105 | 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 | # SPDX-License-Identifier: Apache-2.0
"""OCR an image with a running DeepSeek-OCR server (tt serve changh95/DeepSeek-OCR), standard library only:
python examples/quickstart.py page.png [http://localhost:20000] [markdown|ocr|free|figure|describe] [mode]
It sends the image to the OpenAI-compatible route as a data URL with the task's official prompt 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.",
"ocr": "<image>\n<|grounding|>OCR this image.", "free": "<image>\nFree OCR.",
"figure": "<image>\nParse the figure.", "describe": "<image>\nDescribe this image in detail."}
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 # tiny | small | base | large | gundam (the default)
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", "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()
|