#!/usr/bin/env python3 """Generic OpenAI-chat OCR client for kbench engine comparison. Resumable (skips ids already in OUT). Usage: engine_client.py PAGES_JSON OUT_JSONL URL MODEL PROMPT_KEY MAX_TOKENS(0=server default) WORKERS Row out: {id, text, finish, error, seconds}. temperature 0, repetition_penalty 1.0, no logits processors.""" import base64, json, mimetypes, sys, time, urllib.request from concurrent.futures import ThreadPoolExecutor from pathlib import Path PROMPTS = { # baidu/Unlimited-OCR README single-image prompt (same string as our frozen eval) "unlimited": "document parsing.", # deepseek-ai/DeepSeek-OCR README document prompt; is inserted by the chat template in vLLM chat API "deepseek": "<|grounding|>Convert the document to markdown. ", # ATH-MaaS/OvisOCR2 README prompt "ovis": ("Extract all readable content from the image in natural human reading order and output the result as a " "single Markdown document. For charts or images, represent them using an HTML image tag: , where left, top, right, bottom are bounding box coordinates " "scaled to [0, 1000). Format formulas as LaTeX. Format tables as HTML: ...
. Transcribe all " "other text as standard Markdown. Preserve the original text without translation or paraphrasing."), } pages_path, out_path, url, model, pkey, max_tokens, workers = sys.argv[1:8] max_tokens, workers = int(max_tokens), int(workers); prompt = PROMPTS[pkey] pages = json.load(open(pages_path))["pages"] out = Path(out_path); done = {json.loads(l)["id"] for l in out.open()} if out.exists() else set() todo = [p for p in pages if p["id"] not in done] print(f"pages {len(pages)} done {len(done)} todo {len(todo)}", flush=True) def one(p): t = time.time(); img = Path(p["image"]) mime = mimetypes.guess_type(img.name)[0] or "image/png" payload = {"model": model, "messages": [{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{base64.b64encode(img.read_bytes()).decode()}"}}, {"type": "text", "text": prompt}]}], "temperature": 0, "repetition_penalty": 1.0, "skip_special_tokens": False} if max_tokens: payload["max_tokens"] = max_tokens try: req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=1200) as r: body = json.loads(r.read()) ch = body["choices"][0] return {"id": p["id"], "text": ch["message"]["content"] or "", "finish": ch.get("finish_reason"), "error": None, "seconds": round(time.time() - t, 2)} except Exception as e: msg = repr(e) if hasattr(e, "read"): try: msg += " " + e.read().decode()[:300] except Exception: pass return {"id": p["id"], "text": "", "finish": None, "error": msg[:500], "seconds": round(time.time() - t, 2)} with out.open("a") as f, ThreadPoolExecutor(workers) as ex: for k, row in enumerate(ex.map(one, todo), 1): f.write(json.dumps(row, ensure_ascii=False) + "\n"); f.flush() if k % 200 == 0: print(k, row["id"], row["error"] or row["finish"], row["seconds"], flush=True) print("CLIENT_DONE", flush=True)