콘텐츠로 이동

InferenceHandler

ocr.engine.api.InferenceHandler

NPU edge 추론 기반으로 OCR 기능을 수행하는 InferenceHandler class 입니다.

Usage

main.py / run.py 참고

build(config) classmethod

InferenceHandler instance를 생성합니다.

Parameters:

Name Type Description Default
config dict

InferenceHandler를 build 하기 위한 config dictionary. 세 checkpoint 경로는 필수입니다 — 생략하거나 None 이면 에러입니다.

{
    "det_checkpoint_path": str,          # DET .saigeedge 경로 (필수)
    "ori_checkpoint_path": str,          # ORI .saigeedge 경로 (필수)
    "rec_checkpoint_path": str,          # REC .saigeedge 경로 (ONNX + charset, 필수)
    "password": str | None,              # 세 checkpoint 공용 AES password
}

required

Returns:

Name Type Description
InferenceHandler InferenceHandler

build가 완료된 instance.

Usage
err, msg, handler = InferenceHandler.build({
    "det_checkpoint_path": "/path/to/det.saigeedge",
    "ori_checkpoint_path": "/path/to/ori.saigeedge",
    "rec_checkpoint_path": "/path/to/rec.saigeedge",
    "password": "secret",
})

infer(image, boxes=None)

이미지 1장에 대해 det → ori → rec inference를 수행합니다.

Parameters:

Name Type Description Default
image ndarray

inference를 수행할 BGR uint8 image (shape: [H, W, 3])

required
boxes list | None

읽을 영역을 이미 알고 있는 경우 (4, 2) 폴리곤 list. 지정하면 det / ori 를 생략하고 해당 영역만 인식합니다 (manual mode).

None

Returns:

Name Type Description
OcrResult OcrResult

검사 결과 dataclass. result.to_dict() 로 JSON 직렬화할 수 있으며 schema 는 다음과 같습니다.

{
    "mode": str,            # "auto" (det 수행) | "manual" (boxes 지정)
    "boxes": [              # 인식된 text 단위. det 출력 순서를 유지합니다.
        {
            "polygon": list[list[float]],  # 원본 좌표계 (4, 2) polygon.
                                           # 좌상단부터 시계방향, 회전 가능.
            "text": str,                   # 인식 문자열 (한글 NFC 정규화).
            "confidence": float,           # 0 ~ 1. CTC 채택 문자들의 평균 확률.
            "rotation": int,               # 0 | 180. polygon crop 대비 text 방향.
                                           # polygon 재-crop 시 이만큼 돌리면 정방향.
        },
    ],
    "stages": {             # stage 별 소요 시간 (ms)
        "det_ms": float,    # NPU 검출
        "crop_ms": float,   # crop + 명암 정규화
        "ori_ms": float,    # NPU 방향 판정 (manual mode 면 0)
        "rec_ms": float,    # CPU 인식
        "total_ms": float,  # 위 합 + pipeline overhead
    },
}

Usage
err, msg, result = handler.infer(image)
for box in result.boxes:
    print(box.text, box.confidence)

get_default_inference_option(model, key)

(model, key) inference option 의 기본값을 반환합니다.

Parameters:

Name Type Description Default
model str

"detection" / "orientation" / "recognition" / "ocr".

required
key str

option key — 전체 목록은 :meth:set_inference_option 참고.

required

Returns:

Name Type Description
Any Any

해당 option 의 기본값.

get_inference_option(model, key)

(model, key) inference option 의 현재 값을 반환합니다.

Parameters:

Name Type Description Default
model str

:meth:get_default_inference_option 과 동일.

required
key str

option key.

required

Returns:

Name Type Description
Any Any

현재 설정된 값.

set_inference_option(model, key, value)

runtime inference option 을 설정합니다. 다음 infer 부터 즉시 반영됩니다.

지원하는 (model, key) 조합:

model key 설명 (기본값)
detection params.thresh 확률맵 이진화 임계값 (0.2)
detection params.box_thresh polygon 내부 평균 확률 하한 (0.45)
detection params.unclip_ratio 축소된 text 영역 확장 비율 (2.3)
detection params.max_megapixels 입력 해상도 상한 (1.5)
orientation params.enabled 방향 판정 stage on/off (True)
orientation params.conf_threshold 180° 판정 확신 하한 (0.9)
recognition params.async_enabled crop 이 여럿이면 병렬 인식 (True)
recognition params.async_workers 병렬 worker 수 (8)
recognition params.max_width 입력 폭 상한 px (1600)
recognition params.flip_retry_enabled 확신 낮으면 180° 재시도 (True)
recognition params.flip_conf_threshold 재시도 trigger 확신 (0.9)
ocr params.contrast_norm crop 별 명암 스트레치 (True)

Parameters:

Name Type Description Default
model str

option 을 소유한 model 이름.

required
key str

option key.

required
value Any

새 값. 값 검증은 해당 stage 가 수행합니다.

required

Raises:

Type Description
InvalidInferenceOptionError

지원하지 않는 조합이거나 값이 규격에 맞지 않을 때.

Usage
err, msg, _ = handler.set_inference_option("detection", "params.box_thresh", 0.5)

release()

det/ori inferencer가 잡고 있는 NPU backend 리소스를 해제합니다.

Usage
err, msg, _ = handler.release()

# 또는 context manager 패턴 권장:
with handler:
    err, msg, result = handler.infer(image)
# __exit__에서 release() 자동 호출