""" edkb_system/skills/ocr.py 用途:识别文档图片中的文字,并为 PDF 整页 OCR 保留可复用的行级坐标与原始像素尺寸。 依赖:RapidOCR、Pillow、NumPy、edkb_system.contracts。 逻辑:图片预处理后执行检测与识别;正文继续写入 ocr_text Block,PDF 整页结果额外保存 归一化多边形,供采购合同等下游在原 PDF 上恢复精确高亮坐标。 """ from __future__ import annotations import base64 import io import re from edkb_system.contracts import Block, Context _RAPID_OCR_ENGINE = None _PDF_PAGE_IMAGE_MAX_EDGE = 1800 def _is_meaningful_ocr_line(text: str) -> bool: token = re.sub(r"\s+", "", text or "") if not token or re.fullmatch(r"[\W_]+", token): return False cjk_count = len(re.findall(r"[\u4e00-\u9fff]", token)) alnum_count = len(re.findall(r"[A-Za-z0-9]", token)) if cjk_count >= 2: return True if cjk_count >= 1 and len(token) >= 2: return True if alnum_count >= 5: return True return len(token) >= 4 def _decode_data_uri_image(data_uri: str): m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL) if not m: return None try: raw = base64.b64decode(m.group(1), validate=False) except Exception: return None try: import numpy as np from PIL import Image with Image.open(io.BytesIO(raw)) as im: return np.array(im.convert("RGB")) except Exception: return None def _get_ocr_engine(): global _RAPID_OCR_ENGINE if _RAPID_OCR_ENGINE is not None: return _RAPID_OCR_ENGINE from rapidocr_onnxruntime import RapidOCR # type: ignore _RAPID_OCR_ENGINE = RapidOCR() return _RAPID_OCR_ENGINE def _prepare_image_for_ocr(image_obj, *, pdf_page_image: bool): """限制 PDF 整页图尺寸,兼顾 OCR 速度、内存占用和坐标精度。""" if not pdf_page_image: return image_obj try: import numpy as np from PIL import Image if not hasattr(image_obj, "shape") or len(image_obj.shape) < 2: return image_obj height = int(image_obj.shape[0]) width = int(image_obj.shape[1]) max_edge = max(width, height) if max_edge <= _PDF_PAGE_IMAGE_MAX_EDGE: return image_obj scale = _PDF_PAGE_IMAGE_MAX_EDGE / float(max_edge) target_size = ( max(1, int(round(width * scale))), max(1, int(round(height * scale))), ) pil_image = Image.fromarray(np.asarray(image_obj, dtype=np.uint8)) resized = pil_image.resize(target_size, Image.Resampling.LANCZOS) return np.asarray(resized) except Exception: return image_obj 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]: blocks = input_data try: engine = _get_ocr_engine() except Exception: context.warnings.append("RapidOCR unavailable; skip OCR") return blocks out: list[Block] = [] for b in blocks: out.append(b) if b.type != "image": continue context.images += 1 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 None: out.append( Block( id=f"ocr-{b.id}", page=b.page, type="ocr_text", text="OCR_TEXT: ", bbox=b.bbox, ) ) continue try: 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: " 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}", page=b.page, type="ocr_text", text=text, bbox=b.bbox, meta=output_meta, ) ) except Exception as exc: context.warnings.append(f"OCR failed: {exc}") out.append( Block( id=f"ocr-{b.id}", page=b.page, type="ocr_text", text="OCR_TEXT: ", bbox=b.bbox, ) ) return out