Files
syops/backend/edkb_system/skills/ocr.py
T

167 lines
4.8 KiB
Python

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, block: Block):
meta = getattr(block, "meta", {}) or {}
if not (
meta.get("page_image")
and str(meta.get("page_image_source") or "").lower() == "pdf"
):
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(block: Block) -> dict:
meta = getattr(block, "meta", {}) or {}
if meta.get("page_image") and str(meta.get("page_image_source") or "").lower() == "pdf":
return {"use_det": True, "use_cls": False, "use_rec": True}
return {}
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 not None:
image_obj = _prepare_image_for_ocr(image_obj, b)
if image_obj is None:
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
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)
else:
text = "OCR_TEXT: <empty>"
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text=text,
bbox=b.bbox,
)
)
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: <empty>",
bbox=b.bbox,
)
)
return out