File size: 2,336 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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Quickstart: PaddleOCR-VL served by `tt serve changh95/PaddleOCR-VL` (or `tt-model serve`) on port 20000.

    python3 examples/quickstart.py [image] [task]          # task: ocr | table | formula | chart | spotting | seal

Uses the OpenAI Python client when it is installed (pip install openai), else the standard library.
"""
import base64
import json
import sys
import urllib.request
from pathlib import Path

URL = "http://localhost:20000"
HERE = Path(__file__).resolve().parent
image = Path(sys.argv[1]) if len(sys.argv) > 1 else HERE.parent / "code/tt_paddleocr/samples/table_simple.png"
task = sys.argv[2] if len(sys.argv) > 2 else "table"
prompts = {"ocr": "OCR:", "table": "Table Recognition:", "formula": "Formula Recognition:",
           "chart": "Chart Recognition:", "spotting": "Spotting:", "seal": "Seal Recognition:"}
data_url = "data:image/png;base64," + base64.b64encode(image.read_bytes()).decode()

# 1. OpenAI-compatible chat completions: the text part is the task prompt
messages = [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url}},
                                         {"type": "text", "text": prompts[task]}]}]
try:
    from openai import OpenAI

    client = OpenAI(base_url=URL + "/v1", api_key="unused")
    r = client.chat.completions.create(model="paddleocr-vl", messages=messages, max_tokens=1024)
    print(r.choices[0].message.content)
except ImportError:
    req = urllib.request.Request(URL + "/v1/chat/completions", method="POST",
                                 data=json.dumps({"model": "paddleocr-vl", "messages": messages}).encode(),
                                 headers={"Content-Type": "application/json"})
    print(json.loads(urllib.request.urlopen(req).read())["choices"][0]["message"]["content"])

# 2. the native route: the task view of the answer (table HTML, spotting boxes, LaTeX) and the timings
req = urllib.request.Request(URL + "/ocr", method="POST", headers={"Content-Type": "application/json"},
                             data=json.dumps({"image": data_url, "task": task}).encode())
r = json.loads(urllib.request.urlopen(req).read())
print(json.dumps({"result": r["result"], "timings_ms": r["timings"], "usage": r["usage"]}, ensure_ascii=False,
                 indent=1))