File size: 10,757 Bytes
1e8b5fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python3
"""KoOCR-Bench v1.2 API runs with block boxes (owner 2026-10-05: every engine must be asked for coordinates).
Output per block: <|det|>TYPE [x0, y0, x1, y1]<|/det|>CONTENT, coordinates normalised to 0..999 of the page.
  gemini-*  : PROMPT below (published verbatim in the benchmark README); temperature 0, lowest thinking setting
              (3.1: thinkingBudget 0; 3.5 rejects budget 0, so thinkingLevel "minimal"). A det header the model closed
              with <|det|> or <|/det/> instead of <|/det|> is repaired (CLOSE_FIX) so the block text is not swallowed by the next tag.
  mistral   : mistral-ocr-latest, table_format=html; uses the response's `blocks` (top_left/bottom_right px) in API order,
              table blocks replaced by the returned HTML table.
  clova     : CLOVA OCR V2 general + table detection; words grouped into lines by lineBreak, line box = union of word
              boundingPoly; lines whose centre falls inside a detected table are replaced by that table (HTML) as one
              block; blocks ordered by top y then x.
Raw API responses are kept next to OUT (OUT.raw.jsonl).
Keys/endpoints come from env: GEMINI_API_KEY, MISTRAL_API_KEY, CLOVA_OCR_URL, CLOVA_OCR_SECRET.
Usage: api_run_v3.py ENGINE MANIFEST_JSONL IMG_ROOT OUT_JSONL [THREADS]"""

import base64, html, io, json, os, re, sys, time, uuid, urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from PIL import Image

eng, man, root, out = sys.argv[1], sys.argv[2], Path(sys.argv[3]), Path(sys.argv[4])
threads = int(sys.argv[5]) if len(sys.argv) > 5 else 8
rawf = Path(str(out) + ".raw.jsonl")
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]

PROMPT = "\n".join(
    [
        "이 문서 페이지를 OCR 하라. 페이지를 읽는 순서대로 블록(문단, 제목, 표, 그림, 머리말, 꼬리말, 쪽번호, 수식, 캡션) 단위로 나눠 출력하라.",
        "- 각 블록은 반드시 `<|det|>종류 [x0, y0, x1, y1]<|/det|>내용` 형식으로 한 블록씩 출력하라.",
        "- 종류는 title, text, table, image, header, footer, page_number, equation, caption 중 하나다.",
        "- 좌표는 페이지 왼쪽 위가 (0, 0), 오른쪽 아래가 (999, 999)인 정수다. x0,y0은 블록 왼쪽 위, x1,y1은 오른쪽 아래다.",
        "- 원문 표현은 그대로 보존하라(요약·바꿔쓰기·날조 금지). 보이는 텍스트만.",
        "- 한 문단 안에서 줄이 끊긴 것은 이어 붙여라.",
        "- 표는 HTML <table><tr><td>로 출력하라. 셀 병합은 rowspan/colspan으로 표시하라. Markdown 표 금지.",
        "- 그림은 내용 없이 `<|det|>image [x0, y0, x1, y1]<|/det|>`만 출력하라.",
    ]
)


CLOSE_FIX = re.compile(r"(<\|det\|>\s*\w+\s*\[\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\])\s*<\|?/?det[|/]?>")  # <|det|>, <|/det/> ...


def norm_box(x0, y0, x1, y1, w, h):
    f = lambda v, s: max(0, min(999, int(round(v / max(1, s) * 999))))
    return f(x0, w), f(y0, h), f(x1, w), f(y1, h)


def det(kind, box, content):
    return f"<|det|>{kind} [{box[0]}, {box[1]}, {box[2]}, {box[3]}]<|/det|>{content}"



if eng.startswith("gemini"):
    KEY = os.environ["GEMINI_API_KEY"]
    URL = f"https://generativelanguage.googleapis.com/v1beta/models/{eng}:generateContent?key="
elif eng == "mistral":
    KEY = os.environ["MISTRAL_API_KEY"]
elif eng == "clova":
    CURL, CSEC = os.environ["CLOVA_OCR_URL"], os.environ["CLOVA_OCR_SECRET"]
else:
    raise SystemExit("engine?")


def post(url, body, headers):
    req = urllib.request.Request(
        url,
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json", **headers},
    )
    return json.loads(urllib.request.urlopen(req, timeout=300).read())


def call(r):
    raw = (root / r["image"].lstrip("/")).read_bytes()
    im = Image.open(io.BytesIO(raw))
    W, H = im.size
    fmt = (
        "webp"
        if raw[8:12] == b"WEBP"
        else ("jpeg" if raw[:2] == b"\xff\xd8" else "png")
    )
    if eng.startswith("gemini"):
        body = {
            "contents": [
                {
                    "parts": [
                        {"text": PROMPT},
                        {
                            "inline_data": {
                                "mime_type": f"image/{fmt}",
                                "data": base64.b64encode(raw).decode(),
                            }
                        },
                    ]
                }
            ],
            "generationConfig": {
                "temperature": 0,
                "thinkingConfig": {"thinkingLevel": "minimal"} if eng.startswith("gemini-3.5") else {"thinkingBudget": 0},
                "maxOutputTokens": 60000,
            },
        }
        d = post(URL + KEY, body, {})
        c = d["candidates"][0]
        return (
            CLOSE_FIX.sub(r"\1<|/det|>", "".join(p.get("text", "") for p in c.get("content", {}).get("parts", []))),
            d,
            c.get("finishReason"),
        )
    if eng == "mistral":
        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(),
            },
        }
        d = post(
            "https://api.mistral.ai/v1/ocr", body, {"Authorization": "Bearer " + KEY}
        )
        parts = []
        for p in d.get("pages", []):
            dw, dh = p["dimensions"]["width"], p["dimensions"]["height"]
            tabs = {t["id"]: t.get("content") or "" for t in p.get("tables") or []}
            for b in p.get("blocks") or []:
                box = norm_box(
                    b["top_left_x"],
                    b["top_left_y"],
                    b["bottom_right_x"],
                    b["bottom_right_y"],
                    dw,
                    dh,
                )
                content = (
                    tabs.get(b.get("table_id") or "", None)
                    if b.get("table_id")
                    else None
                )
                if content is None:
                    content = b.get("content") or ""
                parts.append(det(b.get("type") or "text", box, content))
        return "\n".join(parts), d, "ok"
    # clova
    if fmt == "webp" or fmt == "jpeg":
        b = io.BytesIO()
        im.convert("RGB").save(b, "PNG")
        raw = b.getvalue()
    body = {
        "version": "V2",
        "requestId": str(uuid.uuid4()),
        "timestamp": int(time.time() * 1000),
        "lang": "ko",
        "images": [
            {"format": "png", "name": "p", "data": base64.b64encode(raw).decode()}
        ],
        "enableTableDetection": True,
    }
    d = post(CURL, body, {"X-OCR-SECRET": CSEC})
    ci = d["images"][0]
    if ci.get("inferResult") != "SUCCESS":
        raise RuntimeError(f"inferResult {ci.get('inferResult')} {ci.get('message')}")
    poly = lambda bp: (
        [v.get("x", 0) for v in bp["vertices"]],
        [v.get("y", 0) for v in bp["vertices"]],
    )
    tables = []
    for t in ci.get("tables", []):
        xs, ys = poly(t["boundingPoly"])
        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>"
        )
        tables.append(((min(xs), min(ys), max(xs), max(ys)), h))
    blocks, line, lxs, lys = [], [], [], []

    def flush():
        if line:
            x0, y0, x1, y1 = min(lxs), min(lys), max(lxs), max(lys)
            cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
            if not any(a <= cx <= c_ and b <= cy <= d_ for (a, b, c_, d_), _ in tables):
                blocks.append(
                    (
                        (y0, x0),
                        det("text", norm_box(x0, y0, x1, y1, W, H), " ".join(line)),
                    )
                )
        line.clear()
        lxs.clear()
        lys.clear()

    for f in ci.get("fields", []):
        xs, ys = poly(f["boundingPoly"])
        line.append(f["inferText"])
        lxs.extend(xs)
        lys.extend(ys)
        if f.get("lineBreak"):
            flush()
    flush()
    for (a, b, c_, d_), h in tables:
        blocks.append(((b, a), det("table", norm_box(a, b, c_, d_, W, H), h)))
    return "\n".join(x for _, x in sorted(blocks)), d, "SUCCESS"


def work(r):
    t0 = time.time()
    err = None
    for a in range(3):
        try:
            text, d, fin = call(r)
            return {
                "id": r["id"],
                "text": text,
                "finish": fin,
                "error": None,
                "seconds": round(time.time() - t0, 1),
            }, d
        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": "",
        "finish": None,
        "error": err,
        "seconds": round(time.time() - t0, 1),
    }, None


print(eng, "todo", len(todo), "done", len(done), flush=True)
with out.open("a") as f, rawf.open("a") as fr, ThreadPoolExecutor(threads) as ex:
    for k, (row, d) in enumerate(ex.map(work, todo), 1):
        f.write(json.dumps(row, ensure_ascii=False) + "\n")
        f.flush()
        if d is not None:
            fr.write(
                json.dumps({"id": row["id"], "response": d}, ensure_ascii=False) + "\n"
            )
            fr.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)