Datasets:
Download code/engines/api_gemini_clova.py from schift-io/KoOCR-Bench: direct link, hf CLI and curl.
- Browser
- Download file 5.89 kB
-
https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/engines/api_gemini_clova.py
- Command line
-
hf download hf://datasets/schift-io/KoOCR-Bench/code/engines/api_gemini_clova.py
-
curl -L -o api_gemini_clova.py https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/engines/api_gemini_clova.py
5.89 kB
| #!/usr/bin/env python3 | |
| """kobench v1 re-run 2026-10-04: HTML-table prompt (the 09-30 prompt asked Markdown tables). kbench public 604 via external APIs (owner-approved 2026-09-30). Core first, resumable, 3 attempts per page. | |
| Usage: api_run.py gemini|clova OUT_JSONL [THREADS]. Keys are read in-process and never printed.""" | |
| import base64, html, json, subprocess, sys, time, uuid, urllib.request | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| H = Path(__file__).parent; eng, out = sys.argv[1], Path(sys.argv[2]); threads = int(sys.argv[3]) if len(sys.argv) > 3 else 8 | |
| M = [json.loads(l) for l in open(H / "public_manifest.jsonl")] | |
| M.sort(key=lambda r: "core" not in r["tier"]) # core 360 first | |
| import os | |
| if os.environ.get("ONLY_WEBP"): M = [r for r in M if (H / "img" / r["image"].lstrip("/")).read_bytes()[8:12] == b"WEBP"] | |
| 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] | |
| img = lambda r: H / "img" / r["image"].lstrip("/") | |
| def secret(name): | |
| return os.environ[name.upper().replace("-", "_")] | |
| PROMPT = "\n".join(["이 페이지를 OCR 하라. 보이는 한국어 본문/문제/선지를 읽는 순서대로 Markdown으로 출력하라.", | |
| "- 지문은 문단(단락) 구조를 살려라: 한 문단 안에서 OCR로 줄이 끊긴 것은 한 문단으로 자연스럽게 이어 붙이고, 문단과 문단 사이는 빈 줄로 구분하라. 줄바꿈을 있는 그대로 박지 마라.", | |
| "- 원문 표현은 그대로 보존하라(요약·바꿔쓰기·날조 금지). 보이는 텍스트만.", | |
| "- 표는 반드시 HTML <table><tr><td>로 출력하라. 셀 병합은 rowspan/colspan으로 표시하라. Markdown 표(| 구분) 금지.", | |
| "- 제목·소제목은 Markdown #, ## 로 표시하라.", | |
| "- 보기·<보기>·박스는 구조 유지.", | |
| "- 그림/이미지는 base64/data URI 금지. `[그림]` 자리표시자만."]) | |
| if eng == "gemini": | |
| KEY = os.environ["GEMINI_API_KEY"] | |
| URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-lite:generateContent?key=" | |
| else: | |
| CURL, CSEC = os.environ["CLOVA_OCR_URL"], os.environ["CLOVA_OCR_SECRET"] | |
| def call(r): | |
| raw = img(r).read_bytes(); fmt = "webp" if raw[8:12] == b"WEBP" else "png" # some tables images are WEBP bytes under .png names | |
| if eng == "clova" and fmt == "webp": # Clova accepts png/jpg/pdf/tiff only | |
| import io; from PIL import Image; b = io.BytesIO(); Image.open(io.BytesIO(raw)).convert("RGB").save(b, "PNG"); raw, fmt = b.getvalue(), "png" | |
| data = base64.b64encode(raw).decode() | |
| if eng == "gemini": | |
| body = {"contents": [{"parts": [{"text": PROMPT}, {"inline_data": {"mime_type": f"image/{fmt}", "data": data}}]}], | |
| "generationConfig": {"temperature": 0, "thinkingConfig": {"thinkingBudget": 0}, "maxOutputTokens": 60000}} | |
| req = urllib.request.Request(URL + KEY, data=json.dumps(body).encode(), headers={"content-type": "application/json"}) | |
| d = json.loads(urllib.request.urlopen(req, timeout=300).read()); c = d["candidates"][0] | |
| return "".join(p.get("text", "") for p in c.get("content", {}).get("parts", [])), c.get("finishReason"), d.get("usageMetadata", {}) | |
| body = {"version": "V2", "requestId": str(uuid.uuid4()), "timestamp": int(time.time() * 1000), "lang": "ko", | |
| "images": [{"format": "png", "name": "p"}], "enableTableDetection": True} | |
| body["images"][0]["data"] = data | |
| req = urllib.request.Request(CURL, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "X-OCR-SECRET": CSEC}) | |
| d = json.loads(urllib.request.urlopen(req, timeout=300).read()); im = d["images"][0] | |
| if im.get("inferResult") != "SUCCESS": raise RuntimeError(f"inferResult {im.get('inferResult')} {im.get('message')}") | |
| line, lines = [], [] | |
| for f in im.get("fields", []): # words in Clova order; lineBreak ends a line (same as the 06 routine_clova text) | |
| line.append(f["inferText"]) | |
| if f.get("lineBreak"): lines.append(" ".join(line)); line = [] | |
| if line: lines.append(" ".join(line)) | |
| text = "\n".join(lines) | |
| for t in im.get("tables", []): | |
| rows = {} | |
| for c in t.get("cells", []): | |
| txt = " ".join(w["inferText"] for tl in c.get("cellTextLines", []) for w in tl.get("cellWords", [])) | |
| rows.setdefault(c["rowIndex"], []).append((c["columnIndex"], c.get("columnSpan", 1), c.get("rowSpan", 1), txt)) | |
| h = "<table>" + "".join("<tr>" + "".join( | |
| "<td" + (f' colspan="{cs}"' if cs > 1 else "") + (f' rowspan="{rs}"' if rs > 1 else "") + f">{html.escape(tx)}</td>" | |
| for _, cs, rs, tx in sorted(rows[k])) + "</tr>" for k in sorted(rows)) + "</table>" | |
| text += "\n\n" + h | |
| return text, "SUCCESS", {"tables": len(im.get("tables", []))} | |
| def work(r): | |
| t0 = time.time(); err = None | |
| for a in range(3): | |
| try: | |
| text, fin, usage = call(r); return {"id": r["id"], "text": text, "finish": fin, "usage": usage, "error": None, "attempts": a + 1, "seconds": round(time.time() - t0, 1)} | |
| except Exception as e: | |
| err = repr(e)[:200] | |
| if hasattr(e, "read"): | |
| try: err += " " + e.read().decode()[:200] | |
| except Exception: pass | |
| time.sleep(5 * (a + 1)) | |
| return {"id": r["id"], "text": "", "finish": None, "usage": {}, "error": err, "attempts": 3, "seconds": round(time.time() - t0, 1)} | |
| print(f"{eng} 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 row["finish"], row["seconds"], flush=True) | |
| print("API_DONE", eng, flush=True) | |