#!/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()