Datasets:
Download code/engines/api_mistral.py from schift-io/KoOCR-Bench: direct link, hf CLI and curl.
- Browser
- Download file 2.9 kB
-
https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/engines/api_mistral.py
- Command line
-
hf download hf://datasets/schift-io/KoOCR-Bench/code/engines/api_mistral.py
-
curl -L -o api_mistral.py https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/engines/api_mistral.py
2.9 kB
| #!/usr/bin/env python3 | |
| """kobench v1: Mistral OCR on public 604 + handwritten 19 (owner 2026-10-05). Key from env MISTRAL_API_KEY. table_format=html; table placeholders in the page markdown are replaced by the returned HTML tables. | |
| Usage: mistral_run.py MANIFEST_JSONL IMG_ROOT OUT_JSONL [THREADS] [LIMIT]""" | |
| import os, base64, json, re, sys, time, urllib.request | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| man, root, out = sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]); threads = int(sys.argv[4]) if len(sys.argv) > 4 else 6 | |
| limit = int(sys.argv[5]) if len(sys.argv) > 5 else 0 | |
| KEY = os.environ["MISTRAL_API_KEY"] | |
| M = [json.loads(l) for l in open(man)] | |
| done = {json.loads(l)["id"] for l in out.open() if not json.loads(l).get("error")} if out.exists() else set() | |
| todo = [r for r in M if r["id"] not in done][: limit or None] | |
| def call(r): | |
| raw = (root / r["image"].lstrip("/")).read_bytes(); fmt = "webp" if raw[8:12] == b"WEBP" else ("jpeg" if raw[:2] == b"\xff\xd8" else "png") | |
| body = {"model": "mistral-ocr-latest", "table_format": "html", "include_image_base64": False, | |
| "document": {"type": "image_url", "image_url": f"data:image/{fmt};base64," + base64.b64encode(raw).decode()}} | |
| req = urllib.request.Request("https://api.mistral.ai/v1/ocr", data=json.dumps(body).encode(), | |
| headers={"Content-Type": "application/json", "Authorization": "Bearer " + KEY}) | |
| d = json.loads(urllib.request.urlopen(req, timeout=300).read()) | |
| parts = [] | |
| for p in d.get("pages", []): | |
| md = p.get("markdown", "") | |
| for t in p.get("tables", []) or []: | |
| tid, html = t.get("id", ""), t.get("content") or t.get("html") or "" | |
| md = re.sub(r"!?\[[^\]]*\]\(" + re.escape(tid) + r"\)", lambda m: html, md) if tid else md | |
| parts.append(md) | |
| return "\n\n".join(parts), d.get("model"), d.get("usage_info", {}) | |
| def work(r): | |
| t0 = time.time(); err = None | |
| for a in range(3): | |
| try: | |
| text, model, usage = call(r) | |
| return {"id": r["id"], "text": text, "model": model, "usage": usage, "error": None, "seconds": round(time.time() - t0, 1)} | |
| except Exception as e: | |
| err = repr(e)[:200] | |
| if hasattr(e, "read"): | |
| try: err += " " + e.read().decode()[:300] | |
| except Exception: pass | |
| time.sleep(5 * (a + 1)) | |
| return {"id": r["id"], "text": "", "error": err, "seconds": round(time.time() - t0, 1)} | |
| print("mistral todo", len(todo), "done", len(done), flush=True) | |
| with out.open("a") as f, ThreadPoolExecutor(threads) as ex: | |
| for k, row in enumerate(ex.map(work, todo), 1): | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n"); f.flush() | |
| if k % 50 == 0 or row["error"]: print(k, row["id"], row["error"] or "ok", row["seconds"], flush=True) | |
| print("API_DONE mistral", flush=True) | |