Files
syops/backend/edkb_system/skills/ocr.py
T
2026-05-12 08:16:42 +08:00

98 lines
2.7 KiB
Python

from __future__ import annotations
import base64
import io
import re
from edkb_system.contracts import Block, Context
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 run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
blocks = input_data
try:
from rapidocr_onnxruntime import RapidOCR # type: ignore
except Exception:
context.warnings.append("RapidOCR unavailable; skip OCR")
return blocks
engine = RapidOCR()
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: <empty>",
bbox=b.bbox,
)
)
continue
try:
result, _ = engine(image_obj)
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:
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