File size: 1,742 Bytes
6534c46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Send PNG images to llama-server's OpenAI chat-completions endpoint."""

import argparse
import base64
import json
import mimetypes
import time
import urllib.request
from pathlib import Path


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, required=True)
    ap.add_argument("--images", type=Path, required=True)
    ap.add_argument("--prompt", default="Text Recognition:")
    ap.add_argument("--max-tokens", type=int, default=256)
    args = ap.parse_args()
    for image in sorted(args.images.glob("*.png")):
        mime = mimetypes.guess_type(image.name)[0] or "image/png"
        uri = f"data:{mime};base64," + base64.b64encode(image.read_bytes()).decode()
        body = {
            "model": "minicpm-ocr",
            "messages": [{"role": "user", "content": [
                {"type": "image_url", "image_url": {"url": uri}},
                {"type": "text", "text": args.prompt},
            ]}],
            "max_tokens": args.max_tokens,
            "temperature": 0,
            "top_k": 1,
            "seed": 1,
            "cache_prompt": False,
            "chat_template_kwargs": {"enable_thinking": False},
        }
        start = time.time()
        req = urllib.request.Request(
            f"http://127.0.0.1:{args.port}/v1/chat/completions",
            json.dumps(body).encode(),
            {"Content-Type": "application/json"},
        )
        with urllib.request.urlopen(req, timeout=900) as resp:
            result = json.load(resp)
        print(f"=== {image.name} ({time.time() - start:.2f} s) ===", flush=True)
        print(result["choices"][0]["message"].get("content") or "", flush=True)


if __name__ == "__main__":
    main()