Skip to content

vision2

ocr.DetRecInferencer

학습한 모델을 사용하여 검사를 하기 위한 DetRecInferencer class 입니다.

Usage
# 인퍼런스 모듈 빌드
inferene_build_config = {
    "checkpoint_path": CHECKPOINT_PATH,
    "password": PASSWORD,
    "device": DEVICE,
}
error, inferencer = DetRecInferencer.build(inferene_build_config)
assert error >= 0

# 모듈 정보 확인
error, metadata = inferencer.get_metadata()
assert error >= 0
print("Inference metadata:", metadata)

# 인퍼런스 옵션 초기값 확인
error, inference_options = inferencer.get_default_inference_options()
assert error >= 0
print("Inference options:", inference_options)

# 디벨로퍼: Analyze 수행
error, _ = inferencer.set_analysis_data(images=DATA["validation_images"], labeled=True)
assert error >= 0

error, analysis_steps = inferencer.initialize_analysis()
assert error >= 0

for _ in range(analysis_steps):
    error, _ = inferencer.step_analysis()
    assert error >= 0

error, analysis_results = inferencer.finalize_analysis()
assert error >= 0
print("Analysis results:", analysis_results)

# 디벨로퍼: 인퍼런스 옵션 변경
n_classes = CONFIG["n_classes"]
inference_options = {
    "outputs": {
        "mask": True,
        "scoremap": True,
        "objects": True,
    },
    "params": {
        "score_threshold": [50] * n_classes,
        "area_threshold": [10] * n_classes,
        "wo_background": True,
    },
}
error, _ = inferencer.set_inference_options(inference_options)
assert error >= 0

# 인퍼런스 옵션이 잘 변경되었는지 확인
error, inference_options = inferencer.get_inference_options()
assert error >= 0
print("Inference options:", inference_options)

# 디벨로퍼: 새로운 세팅으로 Analyze 재수행
error, analysis_results = inferencer.analyze_with_existing_data()
assert error >= 0
print("Analysis results:", analysis_results)

# 디벨로퍼: 변경된 인퍼런스 옵션으로 체크포인트 다시 저장
error, _ = inferencer.save_checkpoint(
    checkpoint_path=CHECKPOINT_PATH,
    password=PASSWORD,
)
assert error >= 0

# 런타임: 저장된 체크포인트로 핸들러 빌드
error, inferencer = Inferencer.build(inferene_build_config)
assert error >= 0

# 런타임 검사: 후처리까지 한번에 최적화된 연산으로 수행
image_path = DATA["validation_images"][0]["path"]
error, output = inferencer.infer_and_postprocess(images=[image_path])
assert error >= 0
print("Runtime (infer_and_postprocess):", output)

build(config) classmethod

Inferencer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

Inferencer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "checkpoint_path": str,     # 체크포인트 경로
    "password": Optional[str],  # 체크포인트 패스워드 (default None)
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecInferencer class의 instance를 반환합니다.

build_from_checkpoint(config) classmethod

Inferencer class의 instance를 생성합니다. 개별 모듈을 조합해가며 테스트하기 위한 용도의 api method 입니다.

Parameters:

Name Type Description Default
config Dict

Inferencer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "checkpoint_config": {
        "checkpoint_path_det": str,     # SceneTextDetection 체크포인트 경로
        "password_det": Optional[str],  # SceneTextDetection 체크포인트 패스워드 (default None)
        "checkpoint_path_rec": str,     # SceneTextRecognition 체크포인트 경로
        "password_rec": Optional[str],  # SceneTextRecognition 체크포인트 패스워드 (default None)
    },
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecInferencer class의 instance를 반환합니다.

get_metadata()

Trainer.save_checkpoint에서 저장했던 metadata를 반환합니다.

Returns:

Name Type Description
Dict Dict

Trainer.save_checkpoint에서 저장했던 metadata 입니다.

get_inference_options()

현재 설정된 inference & postprocess 옵션들을 dictionary 형태로 반환합니다.

Returns:

Name Type Description
Dict Dict

현재 설정된 inference & postprocess 옵션 정보들이 들어있는 dictionary 입니다.

{
    "detection": {
        "box_confidence_threshold": float,
        "minimum_thickness_threshold": float,
        "absolute_slant_degree_threshold": float,
        "remove_complex_polygon": bool,
    },
    "recognition": {
        "regex": Optional[dict],
        "recognition_confidence_threshold": float
    },
}

get_default_inference_options()

Inference & postprocess 옵션의 기본 설정 값들을 dictionary 형태로 반환합니다.

Returns:

Name Type Description
Dict Dict

Inference & postprocess 옵션의 기본 설정 값들이 들어있는 dictionary 입니다. get_inference_options 의 return dict와 동일한 구조입니다.

set_inference_options(config)

Inference & postprocess 옵션을 설정합니다.

Parameters:

Name Type Description Default
config Dict

설정하고자 하는 Inference & postprocess 옵션 정보가 들어있는 dictionary 입니다. get_inference_options 의 return dict와 동일한 구조이며, 항상 해당 구조의 모든 요소가 포함되어 있어야 합니다.

required

Returns:

Name Type Description
None None

None

infer_and_postprocess(input)

image의 List를 입력으로 받아 모델 인퍼런스와 후처리를 수행합니다. (for Runtime) 실시간 검사를 위해 연산 과정이 최적화되어 있으며, 중간 결과를 제거하고 postprocess 최종 결과만을 반환합니다.

Parameters:

Name Type Description Default
images Union[List[np.ndarray], List[str]]
- List[np.ndarray]: numpy image가 들어있는 List 입니다. 각 image는 다음 제약 조건을 갖습니다.
                    data type: uint8
                    channel: H x W / H x W x 1 - Gray
                             H x W x 3 - RGB
                             H x W x 4 - RGBA
- List[str]: image 경로가 들어있는 List 입니다.
- List[Dict[str, Any]]: 추가적인 정보가 필요한 경우 dict 형태로 입력합니다.
required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict]: image의 postprocess 결과들이 들어있는 List 입니다.

[# TODO: 각 결과값 설명 추가
    {  # 아래 키들 중 inference_options에 설정된 출력 값들만 포함.
        "path": str,  # input image path
        "width": int,  # input image width
        "height": int,  # input image height
        "predictions": [  # OCR 결과 object들의 리스트. (List[Dict])
            {  # ocr object 구조
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
            },
            ...,  # times number of objects
        ],
    },
    ...,  # times number of images
]

set_analysis_data(images, labeled)

Analysis를 위한 data를 세팅합니다. (for Developer)

Parameters:

Name Type Description Default
images List[Dict]

analysis에 사용할 데이터 리스트. Trainer 빌드에 사용하는 이미지 리스트와 동일한 구조.

[
    {
        "path": str,  # 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [  # (labeled = False)인 경우 필요하지 않습니다.
            {
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
            },
            ...,  # times number of labels in the image
        ],
    },
    ...,  # times number of images
]

required
labeled bool

label 존재 여부. label 존재 여부에 따라 analysis 결과 Dict 구성 요소가 달라집니다.

required

Returns:

Name Type Description
None None

None

Note1

Analysis를 위한 api는 정해진 순서대로 호출되어야 하며, 순서를 벗어나는 경우 에러를 raise합니다.

API호출 예시:

inferencer.set_analysis_data(images, labeled)  # 데이터 지정
total_steps = inferencer.initialize_analysis()  # 초기화
for _ in range(total_steps):
    inferencer.step_analysis()  # 정해진 수 만큼 스텝 수행
results = inferencer.finalize_analysis()  # 마무리 & 결과 리턴

inferencer.set_inference_options(options)  # 인퍼런스 옵션 변경
total_steps = inferencer.initialize_analysis()  # 초기화
for _ in range(total_steps):
    inferencer.step_analysis()  # 정해진 수 만큼 스텝 수행
results = inferencer.finalize_analysis()  # 마무리 & 결과 리턴

inferencer.set_inference_options(options)  # 인퍼런스 옵션 변경
results = inferencer.analyze_with_existing_data()  # 초기화 - 스텝 - 마무리를 한 번에 수행 후 결과 리턴

initialize_analysis()

Analysis를 위한 준비 스텝을 수행.

Returns:

Name Type Description
int int

Analysis 완료를 위해 수행되어야 하는 step_analysis 호출 횟수.

step_analysis()

Analysis를 1스텝 수행.

Returns:

Name Type Description
None None

None

finalize_analysis()

Analysis를 마무리하고 결과를 리턴.

Returns:

Name Type Description
Dict Dict

Analysis 결과

{ # TODO: 각 결과값 설명 추가
    "images": [
            {
                "path": "",
                "width": 0,
                "height": 0,
                "predictions": [
                    {
                        "polygon": [
                            [float, float],
                            ..., # times number of points
                        ],
                        "text": str,
                        "det_scores": {
                            "confidence": float,
                            "thickness": float,
                            "slant": float,
                            "simple_contour_flag": bool,
                        },
                        "string_score": float,
                        "is_valid_string": bool,
                        "is_valid_patch": bool,
                    },
                    ..., # 이미지 상의 텍스트 뭉치 수만큼 반복
                ],
            },
            ..., # 입력으로 넣어준 이미지 개수만큼 반복
    ],
    "summary": {  # **(labeled=True)인 경우에만 나옴**
        "Recall": float,
        "Precision": float,
        "Harmonic Mean": float,
        "Recognition Score": float,
    },
}

analyze_with_existing_data()

기존에 세팅된 데이터를 이용해 전체 analysis를 루틴을 수행하고 최종 결과를 리턴.

Note

해당 함수는 아래 루틴을 호출하는 것과 동일함:

total_steps = inferencer.initialize_analysis()  # 초기화
for _ in range(total_steps):
    inferencer.step_analysis()  # 정해진 수 만큼 스텝 수행
results = inferencer.finalize_analysis()  # 마무리 & 결과 리턴

Returns:

Name Type Description
Dict Dict

Analysis 결과 (Inferencer.finalize_analysis 리턴 값과 동일)

save_checkpoint(checkpoint_path, password=None)

현재 inference option 상태를 체크포인트에 업데이트해 저장합니다.

Parameters:

Name Type Description Default
checkpoint_path str

checkpoint를 저장할 path 입니다.

required
password Optional[str]

checkpoint 파일에서 중요한 정보를 암호화 하는데 사용되는 password 입니다. None이면 암호화하지 않습니다. Defaults to None.

None

Returns:

Name Type Description
None

None

ocr.DetRecKieInferencer

학습한 모델을 사용하여 검사를 하기 위한 DetRecKieInferencer class 입니다.

Usage
# 인퍼런스 모듈 빌드
inferene_build_config = {
    "checkpoint_path": CHECKPOINT_PATH,
    "password": PASSWORD,
    "device": DEVICE,
}
error, inferencer = DetRecKieInferencer.build(inferene_build_config)
assert error >= 0

# 모듈 정보 확인
error, metadata = inferencer.get_metadata()
assert error >= 0
print("Inference metadata:", metadata)

# 인퍼런스 옵션 초기값 확인
error, inference_options = inferencer.get_default_inference_options()
assert error >= 0
print("Inference options:", inference_options)

# 디벨로퍼: Analyze 수행
error, _ = inferencer.set_analysis_data(images=DATA["validation_images"], labeled=True)
assert error >= 0

error, analysis_steps = inferencer.initialize_analysis()
assert error >= 0

for _ in range(analysis_steps):
    error, _ = inferencer.step_analysis()
    assert error >= 0

error, analysis_results = inferencer.finalize_analysis()
assert error >= 0
print("Analysis results:", analysis_results)

# 디벨로퍼: 인퍼런스 옵션 변경
n_classes = CONFIG["n_classes"]
inference_options = {
    "outputs": {
        "mask": True,
        "scoremap": True,
        "objects": True,
    },
    "params": {
        "score_threshold": [50] * n_classes,
        "area_threshold": [10] * n_classes,
        "wo_background": True,
    },
}
error, _ = inferencer.set_inference_options(inference_options)
assert error >= 0

# 인퍼런스 옵션이 잘 변경되었는지 확인
error, inference_options = inferencer.get_inference_options()
assert error >= 0
print("Inference options:", inference_options)

# 디벨로퍼: 새로운 세팅으로 Analyze 재수행
error, analysis_results = inferencer.analyze_with_existing_data()
assert error >= 0
print("Analysis results:", analysis_results)

# 디벨로퍼: 변경된 인퍼런스 옵션으로 체크포인트 다시 저장
error, _ = inferencer.save_checkpoint(
    checkpoint_path=CHECKPOINT_PATH,
    password=PASSWORD,
)
assert error >= 0

# 런타임: 저장된 체크포인트로 핸들러 빌드
error, inferencer = Inferencer.build(inferene_build_config)
assert error >= 0

# 런타임 검사: 후처리까지 한번에 최적화된 연산으로 수행
image_path = DATA["validation_images"][0]["path"]
error, output = inferencer.infer_and_postprocess(images=[image_path])
assert error >= 0
print("Runtime (infer_and_postprocess):", output)

build(config) classmethod

Inferencer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

DetRecKieInferencer build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "checkpoint_path": str,     # 체크포인트 경로
    "password": Optional[str],  # 체크포인트 패스워드 (default None)
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecKieInferencer class의 instance를 반환합니다.

build_from_checkpoint(config) classmethod

Inferencer class의 instance를 생성합니다. 개별 모듈을 조합해가며 테스트하기 위한 용도의 api method 입니다.

Parameters:

Name Type Description Default
config Dict

DetRecKieInferencer build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "checkpoint_config": {
        "checkpoint_path_det": str,     # SceneTextDetection 체크포인트 경로
        "password_det": Optional[str],  # SceneTextDetection 체크포인트 패스워드 (default None)
        "checkpoint_path_rec": str,     # SceneTextRecognition 체크포인트 경로
        "password_rec": Optional[str],  # SceneTextRecognition 체크포인트 패스워드 (default None)
        "checkpoint_path_kie": str,     # KeyInformationExtraction 체크포인트 경로
        "password_kie": Optional[str],  # KeyInformationExtraction 체크포인트 패스워드 (default None)
    },
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecKieInferencer class의 instance를 반환합니다.

get_metadata()

Trainer.save_checkpoint에서 저장했던 metadata를 반환합니다.

Returns:

Name Type Description
Dict Dict

Trainer.save_checkpoint에서 저장했던 metadata 입니다.

get_inference_options()

현재 설정된 inference & postprocess 옵션들을 dictionary 형태로 반환합니다.

Returns:

Name Type Description
Dict Dict

현재 설정된 inference & postprocess 옵션 정보들이 들어있는 dictionary 입니다.

{
    "detection": {
        "box_confidence_threshold": float,
        "minimum_thickness_threshold": float,
        "absolute_slant_degree_threshold": float,
        "remove_complex_polygon": bool,
    },
    "recognition": {
        "regex": Optional[dict],
        "recognition_confidence_threshold": float
    },
}

get_default_inference_options()

Inference & postprocess 옵션의 기본 설정 값들을 dictionary 형태로 반환합니다.

Returns:

Name Type Description
Dict Dict

Inference & postprocess 옵션의 기본 설정 값들이 들어있는 dictionary 입니다. get_inference_options 의 return dict와 동일한 구조입니다.

set_inference_options(config)

Inference & postprocess 옵션을 설정합니다.

Parameters:

Name Type Description Default
config Dict

설정하고자 하는 Inference & postprocess 옵션 정보가 들어있는 dictionary 입니다. get_inference_options 의 return dict와 동일한 구조이며, 항상 해당 구조의 모든 요소가 포함되어 있어야 합니다.

required

Returns:

Name Type Description
None None

None

infer_and_postprocess(input)

image의 List를 입력으로 받아 모델 인퍼런스와 후처리를 수행합니다. (for Runtime) 실시간 검사를 위해 연산 과정이 최적화되어 있으며, 중간 결과를 제거하고 postprocess 최종 결과만을 반환합니다.

Parameters:

Name Type Description Default
images Union[List[np.ndarray], List[str]]
- List[np.ndarray]: numpy image가 들어있는 List 입니다. 각 image는 다음 제약 조건을 갖습니다.
                    data type: uint8
                    channel: H x W / H x W x 1 - Gray
                             H x W x 3 - RGB
                             H x W x 4 - RGBA
- List[str]: image 경로가 들어있는 List 입니다.
- List[Dict[str, Any]]: 추가적인 정보가 필요한 경우 dict 형태로 입력합니다.
required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict]: image의 postprocess 결과들이 들어있는 List 입니다.

[# TODO: 각 결과값 설명 추가
    {  # 아래 키들 중 inference_options에 설정된 출력 값들만 포함.
        "path": str,  # input image path
        "width": int,  # input image width
        "height": int,  # input image height
        "predictions": [  # OCR 결과 object들의 리스트. (List[Dict])
            {  # ocr object 구조
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
                "class_index": int,
            },
            ...,  # times number of objects
        ],
    },
    ...,  # times number of images
]

set_analysis_data(images, labeled)

Analysis를 위한 data를 세팅합니다. (for Developer)

Parameters:

Name Type Description Default
images List[Dict]

analysis에 사용할 데이터 리스트. Trainer 빌드에 사용하는 이미지 리스트와 동일한 구조.

[
    {
        "path": str,  # 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [  # (labeled = False)인 경우 필요하지 않습니다.
            {
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
                "class_index": int,
            },
            ...,  # times number of labels in the image
        ],
    },
    ...,  # times number of images
]

required
labeled bool

label 존재 여부. label 존재 여부에 따라 analysis 결과 Dict 구성 요소가 달라집니다.

required

Returns:

Name Type Description
None None

None

Note1

Analysis를 위한 api는 정해진 순서대로 호출되어야 하며, 순서를 벗어나는 경우 에러를 raise합니다.

API호출 예시:

inferencer.set_analysis_data(images, labeled)  # 데이터 지정
total_steps = inferencer.initialize_analysis()  # 초기화
for _ in range(total_steps):
    inferencer.step_analysis()  # 정해진 수 만큼 스텝 수행
results = inferencer.finalize_analysis()  # 마무리 & 결과 리턴

inferencer.set_inference_options(options)  # 인퍼런스 옵션 변경
total_steps = inferencer.initialize_analysis()  # 초기화
for _ in range(total_steps):
    inferencer.step_analysis()  # 정해진 수 만큼 스텝 수행
results = inferencer.finalize_analysis()  # 마무리 & 결과 리턴

inferencer.set_inference_options(options)  # 인퍼런스 옵션 변경
results = inferencer.analyze_with_existing_data()  # 초기화 - 스텝 - 마무리를 한 번에 수행 후 결과 리턴

initialize_analysis()

Analysis를 위한 준비 스텝을 수행.

Returns:

Name Type Description
int int

Analysis 완료를 위해 수행되어야 하는 step_analysis 호출 횟수.

step_analysis()

Analysis를 1스텝 수행.

Returns:

Name Type Description
None None

None

finalize_analysis()

Analysis를 마무리하고 결과를 리턴.

Returns:

Name Type Description
Dict Dict

Analysis 결과

{ # TODO: 각 결과값 설명 추가
    "images": [
            {
                "path": "",
                "width": 0,
                "height": 0,
                "predictions": [
                    {
                        "polygon": [
                            [float, float],
                            ..., # times number of points
                        ],
                        "text": str,
                        "det_scores": {
                            "confidence": float,
                            "thickness": float,
                            "slant": float,
                            "simple_contour_flag": bool,
                        },
                        "string_score": float,
                        "is_valid_string": bool,
                        "is_valid_patch": bool,
                        "class_index": int,
                        # TODO: kie confidence score and postprocessor
                    },
                    ..., # 이미지 상의 텍스트 뭉치 수만큼 반복
                ],
            },
            ..., # 입력으로 넣어준 이미지 개수만큼 반복
    ],
    "summary": {  # **(labeled=True)인 경우에만 나옴**
        "acc_total": float,  # total accuracy
        "acc_key": float,    # key class accuracy
        "acc_value": float,  # value class accuracy
        "sim_total": float,  # total similarity
        "sim_key": float,    # key class similarity
        "sim_value": float,  # value class similarity
    },
}

analyze_with_existing_data()

기존에 세팅된 데이터를 이용해 전체 analysis를 루틴을 수행하고 최종 결과를 리턴.

Note

해당 함수는 아래 루틴을 호출하는 것과 동일함:

total_steps = inferencer.initialize_analysis()  # 초기화
for _ in range(total_steps):
    inferencer.step_analysis()  # 정해진 수 만큼 스텝 수행
results = inferencer.finalize_analysis()  # 마무리 & 결과 리턴

Returns:

Name Type Description
Dict Dict

Analysis 결과 (Inferencer.finalize_analysis 리턴 값과 동일)

save_checkpoint(checkpoint_path, password=None)

현재 inference option 상태를 체크포인트에 업데이트해 저장합니다.

Parameters:

Name Type Description Default
checkpoint_path str

checkpoint를 저장할 path 입니다.

required
password Optional[str]

checkpoint 파일에서 중요한 정보를 암호화 하는데 사용되는 password 입니다. None이면 암호화하지 않습니다. Defaults to None.

None

Returns:

Name Type Description
None

None