File size: 2,784 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
"""OCR a directory of images through llama-server's OpenAI chat endpoint."""

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


def post(url: str, body: dict, timeout: int = 600) -> dict:
    request = urllib.request.Request(
        url,
        json.dumps(body).encode(),
        {"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return json.load(response)


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("--out", type=Path, required=True)
    ap.add_argument("--prompt", default="Text Recognition:")
    ap.add_argument("--max-tokens", type=int, default=256)
    args = ap.parse_args()

    args.out.mkdir(parents=True, exist_ok=True)
    rows = []
    for image_path in sorted(args.images.glob("*.png")):
        mime = mimetypes.guess_type(image_path.name)[0] or "image/png"
        uri = f"data:{mime};base64," + base64.b64encode(image_path.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()
        result = post(f"http://127.0.0.1:{args.port}/v1/chat/completions", body)
        elapsed = time.time() - start
        (args.out / f"{image_path.stem}.json").write_text(
            json.dumps(result, ensure_ascii=False, indent=2) + "\n"
        )
        content = result["choices"][0]["message"].get("content") or ""
        timings = result.get("timings", {})
        row = {
            "image": image_path.name,
            "elapsed_s": elapsed,
            "content": content,
            "prompt_n": timings.get("prompt_n"),
            "prompt_ms": timings.get("prompt_ms"),
            "predicted_n": timings.get("predicted_n"),
            "predicted_ms": timings.get("predicted_ms"),
            "predicted_per_second": timings.get("predicted_per_second"),
            "timings": timings,
        }
        rows.append(row)
        print(json.dumps(row, ensure_ascii=False), flush=True)
    (args.out / "summary.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n")


if __name__ == "__main__":
    main()