# -*- coding: utf-8 -*- """PDF 指定页 -> 300dpi PNG -> RapidOCR -> 行文本 / JSON""" import sys, os, json, io import pymupdf from rapidocr_onnxruntime import RapidOCR BASE = r"C:\Users\MZ\AppData\Local\Temp\cos4std" PDF = os.path.join(BASE, "std.pdf") PG = os.path.join(BASE, "pg2") _ocr = None def get_ocr(): global _ocr if _ocr is None: _ocr = RapidOCR() return _ocr def render(pno, dpi=300): """pno: 1-based PDF 页码""" os.makedirs(PG, exist_ok=True) out = os.path.join(PG, "p%03d.png" % pno) if not os.path.exists(out): d = pymupdf.open(PDF) d[pno - 1].get_pixmap(dpi=dpi).save(out) d.close() return out def ocr_page(pno): png = render(pno) res, _ = get_ocr()(png) items = [] for box, txt, score in (res or []): xs = [float(p[0]) for p in box] ys = [float(p[1]) for p in box] items.append({"t": txt, "x0": min(xs), "x1": max(xs), "y0": min(ys), "y1": max(ys), "s": round(float(score), 3)}) return items def to_lines(items, tol=0.6): """按 y 中心聚行,行内按 x 排序""" its = sorted(items, key=lambda a: (a["y0"], a["x0"])) lines, cur, cy = [], [], None for a in its: c = (a["y0"] + a["y1"]) / 2 h = a["y1"] - a["y0"] if cy is None or abs(c - cy) <= h * tol: cur.append(a) cy = c if not cur[:-1] else (cy + c) / 2 else: lines.append(sorted(cur, key=lambda z: z["x0"])) cur, cy = [a], c if cur: lines.append(sorted(cur, key=lambda z: z["x0"])) return lines if __name__ == "__main__": nos = [] for a in sys.argv[1:]: if "-" in a: s, e = a.split("-") nos.extend(range(int(s), int(e) + 1)) else: nos.append(int(a)) allout = {} for n in nos: its = ocr_page(n) allout["p%03d" % n] = its print("=" * 60, "PDF p%d" % n, "items=%d" % len(its)) for ln in to_lines(its): print(" " + " || ".join(z["t"] for z in ln)) if len(nos) > 1: with open(os.path.join(BASE, "ocr_pages.json"), "w", encoding="utf-8") as f: json.dump(allout, f, ensure_ascii=False) print("-> ocr_pages.json")