from rapidocr_onnxruntime import RapidOCR

from mower.utils import typealias as tp
from mower.utils.log import logger

engine = None


def ocr_rec(img: tp.Image | tp.GrayImage) -> str | None:
    global engine
    if engine is None:
        engine = RapidOCR(text_score=0.3)

    result, elapse = engine(img, use_det=False, use_cls=False, use_rec=True)
    elapse = round(elapse[0] * 1000)
    try:
        text = result[0][0].strip()
    except Exception:
        text = None
    logger.debug(f"{elapse}ms {text}")
    return text
