Datasets:
Download code/engines/api_google_vision.py from schift-io/KoOCR-Bench: direct link, hf CLI and curl.
- Browser
- Download file 3.98 kB
-
https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/engines/api_google_vision.py
- Command line
-
hf download hf://datasets/schift-io/KoOCR-Bench/code/engines/api_google_vision.py
-
curl -L -o api_google_vision.py https://huggingface.co/datasets/schift-io/KoOCR-Bench/resolve/main/code/engines/api_google_vision.py
3.98 kB
| #!/usr/bin/env python3 | |
| """kobench v1: Google Cloud Vision DOCUMENT_TEXT_DETECTION (owner 2026-10-05). Auth: gcloud access token of the active account; quota project from env GOOGLE_CLOUD_PROJECT. Output: one block per Vision block, | |
| "<|det|>text [x0, y0, x1, y1]<|/det|>" (0..999 page-normalised, same as Native) followed by the block text, so the | |
| bbox metric credits Vision's block boxes. Vision has no table structure, so table slices score from text only. | |
| Usage: gvision_run.py MANIFEST_JSONL IMG_ROOT OUT_JSONL [THREADS] [LIMIT]""" | |
| import os, base64, json, subprocess, 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 8 | |
| limit = int(sys.argv[5]) if len(sys.argv) > 5 else 0 | |
| tok = lambda: subprocess.run(["gcloud", "auth", "print-access-token"], capture_output=True, text=True, check=True).stdout.strip() | |
| TOK = [tok(), time.time()] | |
| 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] | |
| BRK = {"SPACE": " ", "SURE_SPACE": " ", "EOL_SURE_SPACE": "\n", "LINE_BREAK": "\n", "HYPHEN": "-\n"} | |
| def block_text(b): | |
| s = [] | |
| for p in b.get("paragraphs", []): | |
| for w in p.get("words", []): | |
| for c in w.get("symbols", []): | |
| s.append(c.get("text", "")); s.append(BRK.get(c.get("property", {}).get("detectedBreak", {}).get("type", ""), "")) | |
| s.append("\n") | |
| return "".join(s).strip() | |
| def call(r): | |
| if time.time() - TOK[1] > 2400: TOK[:] = [tok(), time.time()] | |
| raw = (root / r["image"].lstrip("/")).read_bytes() | |
| body = {"requests": [{"image": {"content": base64.b64encode(raw).decode()}, "features": [{"type": "DOCUMENT_TEXT_DETECTION"}], | |
| "imageContext": {"languageHints": ["ko"]}}]} | |
| req = urllib.request.Request("https://vision.googleapis.com/v1/images:annotate", data=json.dumps(body).encode(), | |
| headers={"Content-Type": "application/json", "Authorization": "Bearer " + TOK[0], "x-goog-user-project": os.environ["GOOGLE_CLOUD_PROJECT"]}) | |
| d = json.loads(urllib.request.urlopen(req, timeout=300).read())["responses"][0] | |
| if d.get("error"): raise RuntimeError(str(d["error"])[:200]) | |
| fta = d.get("fullTextAnnotation") or {} | |
| out = [] | |
| for pg in fta.get("pages", []): | |
| W, H = pg.get("width") or 1, pg.get("height") or 1 | |
| for b in pg.get("blocks", []): | |
| v = b.get("boundingBox", {}).get("vertices", []) | |
| xs = [p.get("x", 0) for p in v] or [0]; ys = [p.get("y", 0) for p in v] or [0] | |
| box = [round(min(xs) / W * 999), round(min(ys) / H * 999), round(max(xs) / W * 999), round(max(ys) / H * 999)] | |
| box = [min(999, max(0, x)) for x in box] | |
| out.append(f"<|det|>text [{box[0]}, {box[1]}, {box[2]}, {box[3]}]<|/det|>{block_text(b)}") | |
| return "\n\n".join(out) | |
| def work(r): | |
| t0 = time.time(); err = None | |
| for a in range(3): | |
| try: | |
| return {"id": r["id"], "text": call(r), "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("gvision 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 gvision", flush=True) | |