fix(contract): 纯图片扫描 PDF 坐标高亮与 OCR 复核

This commit is contained in:
sophie committed 2026-07-29 08:56:13 +08:00
1 parent ca312ea751
commit ce1fd59f61
21 files changed
+1665 -54

No files matched your search

+109 -23
View File
@@ -1,3 +1,12 @@
"""
edkb_system/skills/ocr.py
用途:识别文档图片中的文字,并为 PDF 整页 OCR 保留可复用的行级坐标与原始像素尺寸。
依赖:RapidOCR、Pillow、NumPy、edkb_system.contracts。
逻辑:图片预处理后执行检测与识别;正文继续写入 ocr_text Block,PDF 整页结果额外保存
归一化多边形,供采购合同等下游在原 PDF 上恢复精确高亮坐标。
"""
from __future__ import annotations
import base64
@@ -55,12 +64,9 @@ def _get_ocr_engine():
return _RAPID_OCR_ENGINE
def _prepare_image_for_ocr(image_obj, block: Block):
meta = getattr(block, "meta", {}) or {}
if not (
meta.get("page_image")
and str(meta.get("page_image_source") or "").lower() == "pdf"
):
def _prepare_image_for_ocr(image_obj, *, pdf_page_image: bool):
"""限制 PDF 整页图尺寸,兼顾 OCR 速度、内存占用和坐标精度。"""
if not pdf_page_image:
return image_obj
try:
@@ -87,13 +93,89 @@ def _prepare_image_for_ocr(image_obj, block: Block):
return image_obj
def _ocr_call_kwargs(block: Block) -> dict:
meta = getattr(block, "meta", {}) or {}
if meta.get("page_image") and str(meta.get("page_image_source") or "").lower() == "pdf":
def _ocr_call_kwargs(*, pdf_page_image: bool) -> dict:
"""PDF 整页图强制启用文本检测,确保 RapidOCR 返回行框。"""
if pdf_page_image:
return {"use_det": True, "use_cls": False, "use_rec": True}
return {}
def _normalized_polygon(raw_box, *, width: int, height: int) -> list[list[float]]:
"""把 RapidOCR 像素坐标转换为左上角原点的 0..1 归一化多边形。"""
if width <= 0 or height <= 0 or raw_box is None:
return []
points: list[list[float]] = []
try:
raw_points = list(raw_box)
except TypeError:
return []
for raw_point in raw_points:
try:
if len(raw_point) < 2:
continue
x = min(1.0, max(0.0, float(raw_point[0]) / float(width)))
y = min(1.0, max(0.0, float(raw_point[1]) / float(height)))
except (TypeError, ValueError, IndexError):
continue
points.append([round(x, 6), round(y, 6)])
return points if len(points) >= 4 else []
def recognize_image_lines(
image_obj,
*,
min_confidence: float = 0.3,
pdf_page_image: bool = False,
retain_short_tokens: bool = False,
) -> list[dict]:
"""
识别一张图片并返回文本、置信度和可持久化的行级坐标。
Args:
image_obj: NumPy RGB/BGR 图片;调用方不得传文件路径。
min_confidence: 最低识别置信度,低于阈值的行不会输出。
pdf_page_image: True 表示图片覆盖完整 PDF 页面,坐标可以映射回原 PDF。
retain_short_tokens: True 时保留单个数字等短文本,供表格数量/序号列重建;普通正文默认过滤。
Returns:
按 RapidOCR 阅读顺序排列的行记录;polygon 使用左上角原点的归一化坐标,
pixel_polygon 保留 OCR 输入图像像素坐标,供即时表格行列重建使用。
"""
prepared = _prepare_image_for_ocr(image_obj, pdf_page_image=pdf_page_image)
if prepared is None or not hasattr(prepared, "shape") or len(prepared.shape) < 2:
return []
height = int(prepared.shape[0])
width = int(prepared.shape[1])
engine = _get_ocr_engine()
result, _ = engine(prepared, **_ocr_call_kwargs(pdf_page_image=pdf_page_image))
lines: list[dict] = []
for item in result or []:
if len(item) < 3:
continue
text = str(item[1]).strip()
confidence = float(item[2])
keep_short_token = retain_short_tokens and bool(re.fullmatch(r"[A-Za-z0-9]+", text))
if not text or confidence < min_confidence or (not keep_short_token and not _is_meaningful_ocr_line(text)):
continue
line = {"text": text, "confidence": round(confidence, 6)}
if pdf_page_image:
polygon = _normalized_polygon(item[0], width=width, height=height)
if polygon:
line["polygon"] = polygon
try:
pixel_polygon = [
[round(float(point[0]), 3), round(float(point[1]), 3)]
for point in list(item[0])
if len(point) >= 2
]
except (TypeError, ValueError, IndexError):
pixel_polygon = []
if len(pixel_polygon) >= 4:
line["pixel_polygon"] = pixel_polygon
lines.append(line)
return lines
def run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
@@ -113,8 +195,6 @@ def run(
image_obj = b.meta.get("image")
if image_obj is None and b.meta and b.meta.get("data_uri"):
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
if image_obj is not None:
image_obj = _prepare_image_for_ocr(image_obj, b)
if image_obj is None:
out.append(
Block(
@@ -128,20 +208,25 @@ def run(
continue
try:
result, _ = engine(image_obj, **_ocr_call_kwargs(b))
lines = []
for it in result or []:
if len(it) < 3:
continue
txt = str(it[1]).strip()
conf = float(it[2])
if txt and conf >= min_confidence and _is_meaningful_ocr_line(txt):
lines.append(txt)
if lines:
text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines)
context.ocr_characters += sum(len(x) for x in lines)
meta = getattr(b, "meta", {}) or {}
pdf_page_image = bool(
meta.get("page_image")
and str(meta.get("page_image_source") or "").lower() == "pdf"
)
line_records = recognize_image_lines(
image_obj,
min_confidence=min_confidence,
pdf_page_image=pdf_page_image,
)
line_texts = [str(item["text"]) for item in line_records]
if line_texts:
text = "OCR_TEXT:\n" + "\n".join(f"- {value}" for value in line_texts)
context.ocr_characters += sum(len(value) for value in line_texts)
else:
text = "OCR_TEXT: <empty>"
output_meta = {"source_image_id": b.id}
if pdf_page_image:
output_meta.update({"page_image": True, "ocr_lines": line_records})
out.append(
Block(
id=f"ocr-{b.id}",
@@ -149,6 +234,7 @@ def run(
type="ocr_text",
text=text,
bbox=b.bbox,
meta=output_meta,
)
)
except Exception as exc: