Files
37duAutomation/tests/aitable_probe/ocr_probe.py
T

62 lines
2.0 KiB
Python

# -*- coding: utf-8 -*-
"""OCR 可行性探针:对已落盘的身份证/银行卡照片跑 RapidOCR,打印原始识别结果。
用法(仓库根):
.venv\\Scripts\\python.exe tests\\aitable_probe\\ocr_probe.py # 全部样本
.venv\\Scripts\\python.exe tests\\aitable_probe\\ocr_probe.py --mark # 额外输出标注图
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
REPO_ROOT = HERE.parents[1]
sys.path.insert(0, str(REPO_ROOT / "libs" / "desktopauto"))
from desktopauto import ocr # noqa: E402
OUT = HERE / "_out"
IMG_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
def main() -> int:
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
ap = argparse.ArgumentParser()
ap.add_argument("--mark", action="store_true", help="输出标注图到 _out_marked/")
ap.add_argument("--min-score", type=float, default=0.0)
args = ap.parse_args()
files = sorted(p for p in OUT.rglob("*") if p.is_file() and p.suffix.lower() in IMG_EXT)
print(f"待识别 {len(files)} 张图,输出目录 {OUT}")
t_all = time.time()
marked_dir = OUT.parent / "_out_marked"
for i, p in enumerate(files, 1):
rel = p.relative_to(OUT).as_posix()
t0 = time.time()
try:
items = ocr.recognize(str(p), min_score=args.min_score)
except Exception as e: # noqa: BLE001
print(f"\n[{i}/{len(files)}] {rel} !! 失败:{e}")
continue
dt = time.time() - t0
print(f"\n[{i}/{len(files)}] {rel} ({dt:.1f}s, {len(items)} 段)")
for it in items:
print(f" {it.score:.2f} ({it.left},{it.top},{it.width}x{it.height}) {it.text}")
if args.mark:
out = marked_dir / (rel.replace("/", "_") + ".marked.png")
ocr.mark_text(str(p), items, str(out))
print(f"\n总耗时 {time.time() - t_all:.1f}s")
return 0
if __name__ == "__main__":
raise SystemExit(main())