zheqiushui's picture
AX8860 llama.cpp package
6534c46 verified
Raw History Blame Contribute Delete
2.78 kB
#!/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()