CLOVA OCR Custom API
    • PDF

    CLOVA OCR Custom API

    • PDF

    Article Summary

    version

    VersionDateChanges
    v1.0.02019-12-05최초 작성
    V1.0.12020-02-21General API 호출응답에 boundingPoly 정보 제공
    V2.0.02020-03-26CLOVA OCR 프리미엄 모델 제공으로 멀티박스, 체크박스 인식 기능 추가됨
    요청 버전에 따라 (V1/V2) 인식 결과로 bounding/boundingPoly 정보가 제공됨
    V2 사용을 권장하며 V2 사용 시 boundingPoly 정보가 제공됨
    V2.0.12021-01-21General API JSON 줄바꿈 정보 제공
    Delete subFiled in ImageField object
    V2.0.22021-02-04add convertedImageInfo field in Recognition Results Object
    V2.0.32021-05-27add combineResult field and lineBreak for infer api
    V2.0.42021-07-22lang setting add zh-TW support
    V2.0.52021-09-16general table detection
    V2.0.62023-02-16multi-language support

    요청

    MethodRequest URI
    POSTCLOVA OCR 빌더에서 생성된 API Gateway의 InvokeURL로 호출
    각 도메인마다 고유의 호출 URL이 생성됨

    TEXT OCR 인식과 Template OCR 인식 요청

    구분설명PathRequestResponse
    TEXT OCR템플릿 정의없이 이미지의 모든 텍스트를 인식/general이미지 인식 요청 형식을 따름이미지 인식 결과 형식을 따름
    matchedTemplate, title and validationResult 값은 전달되지 않음
    Template OCR도메인에 배포된 템플릿이 포함 된 이미지를 인식함/infer이미지 인식 요청 형식을 따름이미지 인식 결과 형식을 따름

    요청 헤더

    헤더명설명
    X-OCR-SECRET도메인에서 API Gateway 연동 시 생성한 X-OCR-SECRET:{Client Secret}
    Content-Typeapplication/json : request use json body. Support images.url or images.data encoded with base64.
    - multipart/form-data : request use multipart form body. Support image file transferred as stream.

    요청 바디

    Content-Type : application/json

    1. 이미지 인식 요청
    구분Json Model
    이미지 인식 요청{
    "version": "string",
    "requestId": "string",
    "timestamp": 0,
    "lang": "string",
    "images": [{ "format": "string", "url": "string", "data": "string", "name": "string", "templateIds": [ 0 ] }],
    "enableTableDetection": true
    }

    이미지 인식 요청 필드 상세 설명

    필드명필수 여부타입설명제약 사항
    versionYesstring버전 정보 필수로 V1, 혹은 V2를 입력
    V2 사용을 권장함
    V2사용 시 boundingPoly 정보가 제공됨
    requestIdYesstringAPI 호출 UUID
    timestampYes0API 호출 Timestamp 값
    langNostringOCR 인식 시 요청할 언어 정보설정 가능한 언어값: 'ko'/'ja'/'zh-TW'
    lang 필드가 설정되지 않은 경우 도메인의 언어 설정값이 default로 설정됨
    imagesYesstringJson array로 입력됨
    현재는 1개의 이미지 입력만 허용됨 (한국어/일본어)
    General OCR은 50MB, Template OCR은 20MB (pdf,tiff는 50MB)까지 지원
    images.formatYesstring이미지 포맷을 설정“jpg”, “jpeg”, “png”, "pdf","tiff" 이미지 포맷 지원. General OCR: 최대 10페이지의 pdf 인식 지원, Template OCR: 최대 5페이지의 pdf/tiff 인식 지원
    images.urlNostringimages.url 혹은 images.data 중 하나가 존재해야 함URL은 이미지를 가져 올 수 있는 공개 URL이어야 함
    images.dataNostringimages.url 혹은 images.data 중 하나가 존재해야 함
    URL과 데이터가 모두 존재하면 데이터를 사용하고 URL은 무시
    images.data는 base64 인코딩 이미지 바이트
    images.nameYesstring이미지 명 입력
    이미지를 식별 및 응답 결과 확인에 사용됨
    images.templateIdsNojson array텍스트 OCR API에서는 사용되지 않음
    Template OCR API에서는 이 필드를 설정하지 않을 경우 도메인에 배포된 모든 서비스 템플릿으로 자동 분류됨
    enableTableDetectionNoBoolean문서 내 표(Table) 영역을 자동 인식 후 글자(Text)와 함께 구조화된 형태로 제공Only GENERAL domain support.

    CURL example:

    curl --request POST 'your apigw invoke url' \
    --header 'X-OCR-SECRET: your secret key' \
    --data-raw '{"images":[{"format":"jpg","name":"demo","url":"your image url"}],"requestId":"guide-json-demo","version":"V2","timestamp":1584062336793}'
    

    Content-Type : multipart/form-data

    1. Image Recognition Request
    KEYRequiredVALUE
    messageY{"version": "string","requestId": "string","timestamp": 0,"lang": "string","images": [{ "format": "string", "name": "string", "templateIds": [ 0 ] }]}
    fileYimage file steam data

    Form Data Message Value Description

    Field nameRequiredTypeDescriptionConstraints
    versionYesstring버전 정보 필수로 V1, 혹은 V2를 입력- V2 사용을 권장
    - V2사용 시 boundingPoly 정보가 제공됨
    requestIdYesstringAPI 호출 UUID
    timestampYesintegerAPI 호출 Timestamp 값입
    langNostringOCR 인식시 요청할 언어 정보설정 가능한 언어값은 'ko'/'ja'/'zh-TW' 이며, lang 필드가 설정되지 않은 경우, 도메인의 언어 설정값이 default로 설정됨.
    Use comma(,) in multi-language.ex:"ko,ja,zh-TW"
    imagesYesstringJson array로 입력됨
    현재는 1개의 이미지 입력만 허용됨 (한국어/일본어)
    General OCR은 50MB, Template OCR은 20MB (pdf,tiff는 50MB)까지 지원
    images.formatYesstring이미지 포맷 설정“jpg”, “jpeg”, “png”, "pdf","tiff" 이미지 포맷 지원. General OCR: 최대 10페이지의 pdf 인식 지원, Template OCR: 최대 5페이지의 pdf/tiff 인식 지원
    images.nameYesstring이미지 명 입력
    이미지를 식별 및 응답 결과 확인에 사용함
    images.templateIdsNojson array텍스트 OCR API에서는 사용되지 않음
    Template OCR API에서는 이 필드를 설정하지 않으면 도메인에 배포된 모든 서비스 템플릿으로 자동 분류됨
    enableTableDetectionNoBoolean문서 내 표(Table) 영역을 자동 인식 후 글자(Text)와 함께 구조화된 형태로 제공Only GENERAL domain support.

    CURL example:

    curl --request POST 'your apigw invoke url' \
    --header 'X-OCR-SECRET: your secret key' \
    --form 'message={"images":[{"format":"png","name":"demo"}],"requestId":"guide-demo","version":"V2","timestamp":1584062336793}' \
    --form 'file=@image.png'
    

    응답

    V1 응답 바디

    Request version is 'V1'

    1. 이미지 인식 결과
    구분Json Model
    이미지 인식 결과{
    "uid": "string",
    "name": "string",
    "inferResult": "string",
    "message": "string",
    "matchedTemplate": { "id": 0, "name": "string" },
    "title": {},
    "fields": [ {} ],
    "validationResult": { "result": "string", "message": "string"}
    }

    이미지 인식 결과 필드 상세 설명

    필드 이름데이터 타입설명
    uidstring- API의 유효성을 검사하기 위해 제공되는 고유 ID
    유효성 검사 요청을 추적하는 데 사용됨
    namestring요청한 이미지 이름
    inferResultstring- 이미지 추론 결과
    SUCCESS: 이미지 인식 성공
    FAILURE: 이미지 인식 실패
    ERROR: Image recognition exception.
    messagestring이미지 인식 성공 시 "SUCCESS"
    이미지 인식 실패의 경우 오류 메시지가 표시됨
    오류 메시지는 하단에 자세하게 안내
    matchedTemplatejson object이미지 인식에 일치한 템플릿 정보로 템플릿 ID와 이름을 포함함
    추론이 실패하거나 일치하는 템플릿을 찾을 수없는 경우이 필드에 응답하지 않음
    matchedTemplate.id0템플릿 ID
    matchedTemplate.namestring템플릿 이름
    titlestring이미지 타이틀
    fieldsJson array objectImageField 객체 참조
    validationResultjson object유효성 검사 결과
    validationResult.resultstring- 결과 코드
    NO_REQUESTED: 검증 작업이 실행되지 않음
    UNCHECKED: 동작 응답이 확인되지 않았거나 응답이 수락되지 않음
    - ERROR: 검증 실행에 오류가 발생
    VALID: 검증 결과 유효함
    INVALID: 검증 결과가 유효하지 않음
    UNCHECHED, ERROR, INVALID: 유효성 검사 실패로 표시됨
    validationResult.messagestringValidation 세부 메시지로 항상 응답되는 값은 아님
    combineResultjson object판독 결과 결합
    combineResult.namestring결합 필드 이름
    combineResult.textstring각 필드 별 출력 값+고정 TEXT
    1. ImageField 객체
    구분Json Model
    Image Field{
    "name": "string",
    "valueType": "string",
    "inferText": "string",
    "inferConfidence": 0.0,
    "bounding": {}
    }

    ImageField 객체 필드 상세 설명

    필드 이름데이터 타입설명
    namestring이미지 명
    valueTypestring항상 리턴되는 값은 아니며 필드의 텍스트 값 유형 (ALL: 텍스트와 숫자)
    inferTextstring인식결과 텍스트
    inferConfidence0.0유추 된 결과에 대한 확신
    0-1 값이 클수록 더 정확함
    boundingbounding 객체bounding 객체 참조
    1. bounding객체
    구분Json Model
    bounding{
    "top": 0.0,
    "left": 0.0,
    "width": 0.0,
    "height": 0.0
    }

    bounding 객체 필드 상세 설명

    필드 이름데이터 타입설명
    top0.0Bounding Y 좌표
    left0.0Bounding X 좌표
    width0.0Bounding width.
    height0.0Bounding height.

    V2 응답 바디

    Request version is 'V2'

    1. Image Recognition Results
    ClassificationJson Model
    Image Recognition Results{
    "uid": "string",
    "name": "string",
    "inferResult": "string",
    "message": "string",
    "matchedTemplate": { "id": 0, "name": "string" },
    "title": {},
    "fields": [ {} ],
    "validationResult": { "result": "string", "message": "string"}
    }

    Detailed description of the Image Recognition Results field

    Field NameData TypeDescription
    uidstringA unique ID that is provided to validate the API, which is used to track validation requests.
    namestringThe requested image name.
    inferResultstringImage inference result.
    "SUCCESS": Image recognition successful. “FAILURE”: Image recognition failed.“ERROR”: Image recognition exception.No charge when ERROR.
    messagestringSuccessful image recognition, "SUCCESS"
    If image recognition fails, an error message is displayed.
    Error messages are detailed at the bottom
    matchedTemplatejson objectInclude the template ID and name with template information that matches image recognition.
    This field does not respond if recognition fails or a matched template cannot be found.
    matchedTemplate.idintegerTemplate ID.
    matchedTemplate.namestringName of the template.
    titlejson objectImageField Object Reference
    fieldsJson array objectImageField Object Reference
    validationResultjson objectValidation result.
    validationResult.resultstringResult Code.
    “NO_REQUESTED”: The validation task did not run.
    “UNCHECKED”: Action response not confirmed or not accepted
    “ERROR”: Error executing validation.
    “VALID”: The verification result is valid.
    “INVALID”: The verification result is invalid.
    “UNCHECHED”,“ERROR” and “INVALID” are marked as validation failures.
    validationResult.messagestringIt is not always the value that is returned in the Validation detail message.
    convertedImageInfojson objectOnly response when image format is pdf/tiff.
    Coordinates are based on converted image when request format is pdf/tiff.
    convertedImageInfo.widthintegerThe base image width.
    convertedImageInfo.heightintegerThe base image height.
    convertedImageInfo.pageIndexintegerThe page index of pdf/tiff.
    combineResultjson object판독 결과 결합
    combineResult.namestring결합 필드 이름
    combineResult.textstring각 필드 별 출력 값+고정 TEXT
    tablesJson array objectImageTable Object Reference
    1. ImageField object
    ClassificationJson Model
    Image Field{
    "name": "string",
    "valueType": "string",
    "inferText": "string",
    "inferConfidence": 0.0,
    "boundingPoly": {},
    "type": "string",
    "subFields": [{}],
    "checked":true,
    "lineBreak":true
    }

    ImageField Object Field Details

    Field NameData TypeDescription
    namestringImage name.
    valueTypestringIt is the text value type of the field.
    "ALL": text and numbers
    "NUMERIC":numbers
    inferTextstringRecognition Result Text
    When type is checkbox , it will be replaced by the return value in the setting
    inferConfidencefloatConfidence of infer result. Larger values of 0-1 are more accurate.
    boundingPolyboundingPoly ObjectboundingPoly Object reference
    typestring- NORMAL
    - MULTI_BOX
    - CHECKBOX
    checkedbooleanOnly 'CHECKBOX' type supported.
    Whether the field is checked or not.
    lineBreakbooleanOnly response in GENERAL api.
    Whether there is a newline after the text
    subFieldsJson ArrayOnly response in Template api.
    SubField Object reference
    1. boundingPoly object
    ClassificationJson Model
    boundingPoly{
    "vertices":[{}]
    }

    boundingPoly Object Field Details

    Field NameData TypeDescription
    verticesvertices objectvertices object reference
    1. vertices object
    ClassificationJson Model
    vertices{
    "x": 0.0,
    "y": 0.0
    }

    vertices Object Field Details

    Field NameData TypeDescription
    xfloatX coodinate
    yfloaty coodinate
    1. SubField Object
    ClassificationJson Model
    subField{
    "boundingPoly": {},
    "inferText": "string",
    "inferConfidence":0.0
    "lineBreak": false
    }

    subField Object Field Details

    Field NameData TypeDescription
    boundingPolyboundingPoly ObjectboundingPoly Object reference
    inferTextstringRecognition Result Text
    inferConfidencefloatConfidence of infer result. Larger values of 0-1 are more accurate.
    lineBreakbooleanWhether there is a newline after the text
    1. ImageTable Object
    ClassificationJson Model
    subField{
    "cells": [],
    "boundingPoly": {},
    "inferConfidence":0.0
    }

    ImageTable Object Field Details

    Field NameData TypeDescription
    boundingPolyboundingPoly ObjectboundingPoly Object reference
    cellsjson array objectTableCell Object reference
    inferConfidencefloatConfidence of infer result. Larger values of 0-1 are more accurate.
    1. TableCell Object
    ClassificationJson Model
    subField{
    "cellTextLines": [],
    "boundingPoly": {},
    "inferConfidence":0.0,
    "rowSpan":0,
    "rowIndex":0,
    "columnSpan":0,
    "columnIndex":0
    }

    TableCell Object Field Details

    Field NameData TypeDescription
    boundingPolyboundingPoly ObjectboundingPoly Object reference
    cellTextLinesjson array objectThe lines in a cell.
    CellTextLine Object reference.
    inferConfidencefloatConfidence of infer result. Larger values of 0-1 are more accurate.
    rowSpanintThe rowSpan property specifies the number of rows a cell should span.
    rowIndexintThe rowIndex property specifies the position of a row in the rows collection of a table.
    columnSpanintThe columnSpan property specifies how many columns an element should span across.
    columnIndexintThe columnIndex property specifies the position of a column in the columns collection of a table.
    1. CellTextLine Object
    ClassificationJson Model
    subField{
    "cellWords": [],
    "boundingPoly": {},
    "inferConfidence":0.0
    }

    CellTextLine Object Field Details

    Field NameData TypeDescription
    boundingPolyboundingPoly ObjectboundingPoly Object reference
    inferConfidencefloatConfidence of infer result. Larger values of 0-1 are more accurate.
    cellWordsjson array objectThe words in a line.
    CellWord Object reference.
    1. CellWord Object
    ClassificationJson Model
    subField{
    "inferText": "",
    "boundingPoly": {},
    "inferConfidence":0.0
    }

    CellWord Object Field Details

    Field NameData TypeDescription
    boundingPolyboundingPoly ObjectboundingPoly Object reference
    inferConfidencefloatConfidence of infer result. Larger values of 0-1 are more accurate.
    inferTextstring인식결과 텍스트

    예시

    TEXT OCR 요청 예시

    {
      "version": "V2",
      "requestId": "string",
      "timestamp": 0,
      "lang":"ko",
      "images": [
        {
          "format": "jpg",
          "name": "test 1",
          "url": "https://www.ncloud.com/ocr-test/test.jpg"
        }
      ]
    }
    

    TEXT OCR 응답 예시

    {
        "version": "V2",
        "requestId": "string",
        "timestamp": 1576569034247,
        "images": [{
            "uid": "9fd73a6aacad4025b3099a36ee55aacd",
            "name": "medium",
            "inferResult": "SUCCESS",
            "message": "SUCCESS",
            "fields": [{
                    "valueType": "ALL",
                    "inferText": "아름다운",
                    "inferConfidence": 0.99992156,
                    "type": "NORMAL",
                    "lineBreak": true,
                    "boundingPoly": {
                        "vertices": [{
                            "x": 2713.7295,
                            "y": 1277.0492
                        }, {
                            "x": 2713.7295,
                            "y": 977.7408
                        }, {
                            "x": 2841.4343,
                            "y": 977.7408
                        }, {
                            "x": 2841.4343,
                            "y": 1277.0492
                        }]
                    }
                },
                {
                    "valueType": "ALL",
                    "inferText": "이",
                    "inferConfidence": 0.99958915,
                    "type": "NORMAL",
                    "lineBreak": false,
                    "boundingPoly": {
                        "vertices": [{
                            "x": 2314.6516,
                            "y": 1468.6066
                        }, {
                            "x": 2314.6516,
                            "y": 1328.9293
                        }, {
                            "x": 2426.3936,
                            "y": 1328.9293
                        }, {
                            "x": 2426.3936,
                            "y": 1468.6066
                        }]
                    }
                },
                {
                    "valueType": "ALL",
                    "inferText": "세상",
                    "inferConfidence": 0.9998707,
                    "type": "NORMAL",
                    "lineBreak": false,
                    "boundingPoly": {
                        "vertices": [{
                            "x": 2314.6516,
                            "y": 1604.2931
                        }, {
                            "x": 2314.6516,
                            "y": 1460.625
                        }, {
                            "x": 2430.3843,
                            "y": 1460.625
                        }, {
                            "x": 2430.3843,
                            "y": 1604.2931
                        }]
                    }
                }
            ],
            "validationResult": {
                "result": "NO_REQUESTED"
            }
        }]
    }
    

    Template OCR 요청 예시

    {
      "version": "V1",
      "requestId": "string",
      "timestamp": 0,
      "lang":"ko",
      "images": [
        {
          "format": "jpg",
          "name": "test 1",
          "url": "https://www.ncloud.com/ocr-test/test.jpg",
          "templateIds":[390]
        }
      ]
    }
    

    Template OCR 응답 예시

    {
        "version": "V2",
        "requestId": "string",
        "timestamp": 1584067653255,
        "images": [
            {
                "uid": "1b220cd049de4a7c9e0dc1942d982867",
                "name": "test 1",
                "inferResult": "SUCCESS",
                "message": "SUCCESS",
                "matchedTemplate": {
                    "id": 390,
                    "name": "template"
                },
                "validationResult": {
                    "result": "NO_REQUESTED"
                },
                "title": {
                    "name": "title",
                    "boundingPoly": {
                        "vertices": [
                            {
                                "x": 453.7125,
                                "y": 54.1125
                            },
                            {
                                "x": 961.5375,
                                "y": 54.1125
                            },
                            {
                                "x": 961.5375,
                                "y": 108.225
                            },
                            {
                                "x": 453.7125,
                                "y": 108.225
                            }
                        ]
                    },
                    "inferText": "보험금 청구서 (인보험月)",
                    "inferConfidence": 0.94674826
                },
                "fields": [
                    {
                        "name": "id",
                        "valueType": "NUMERIC",
                        "boundingPoly": {
                            "vertices": [
                                {
                                    "x": 488.88235,
                                    "y": 284.92896
                                },
                                {
                                    "x": 550.3732,
                                    "y": 284.93716
                                },
                                {
                                    "x": 550.39166,
                                    "y": 333.93698
                                },
                                {
                                    "x": 488.90073,
                                    "y": 333.9292
                                }
                            ]
                        },
                        "inferText": "102831",
                        "inferConfidence": 0.9319761,
                        "type": "MULTI_BOX",
                        "subFields": [
                            {
                                "boundingPoly": {
                                    "vertices": [
                                        {
                                            "x": 488.88235,
                                            "y": 284.92896
                                        },
                                        {
                                            "x": 550.3732,
                                            "y": 284.93716
                                        },
                                        {
                                            "x": 550.39166,
                                            "y": 333.93698
                                        },
                                        {
                                            "x": 488.90073,
                                            "y": 333.9292
                                        }
                                    ]
                                },
                                "inferText": "1",
                                "inferConfidence": 0.9798796
                            },
                            {
                                "boundingPoly": {
                                    "vertices": [
                                        {
                                            "x": 551.37305,
                                            "y": 284.9373
                                        },
                                        {
                                            "x": 612.86285,
                                            "y": 284.9455
                                        },
                                        {
                                            "x": 612.88153,
                                            "y": 333.94495
                                        },
                                        {
                                            "x": 551.39154,
                                            "y": 333.9371
                                        }
                                    ]
                                },
                                "inferText": "0",
                                "inferConfidence": 0.6391636
                            },
                            {
                                "boundingPoly": {
                                    "vertices": [
                                        {
                                            "x": 613.86273,
                                            "y": 284.94562
                                        },
                                        {
                                            "x": 675.3515,
                                            "y": 284.95383
                                        },
                                        {
                                            "x": 675.3702,
                                            "y": 333.95288
                                        },
                                        {
                                            "x": 613.8812,
                                            "y": 333.94504
                                        }
                                    ]
                                },
                                "inferText": "2",
                                "inferConfidence": 0.99591047
                            },
                            {
                                "boundingPoly": {
                                    "vertices": [
                                        {
                                            "x": 676.3513,
                                            "y": 284.95395
                                        },
                                        {
                                            "x": 737.8392,
                                            "y": 284.9622
                                        },
                                        {
                                            "x": 737.8579,
                                            "y": 333.96082
                                        },
                                        {
                                            "x": 676.37006,
                                            "y": 333.953
                                        }
                                    ]
                                },
                                "inferText": "8",
                                "inferConfidence": 0.99782735
                            },
                            {
                                "boundingPoly": {
                                    "vertices": [
                                        {
                                            "x": 738.83887,
                                            "y": 284.96228
                                        },
                                        {
                                            "x": 800.3257,
                                            "y": 284.97052
                                        },
                                        {
                                            "x": 800.34454,
                                            "y": 333.96872
                                        },
                                        {
                                            "x": 738.8577,
                                            "y": 333.9609
                                        }
                                    ]
                                },
                                "inferText": "3",
                                "inferConfidence": 0.99916536
                            },
                            {
                                "boundingPoly": {
                                    "vertices": [
                                        {
                                            "x": 801.3255,
                                            "y": 284.97064
                                        },
                                        {
                                            "x": 862.8112,
                                            "y": 284.97882
                                        },
                                        {
                                            "x": 862.8301,
                                            "y": 333.97662
                                        },
                                        {
                                            "x": 801.3443,
                                            "y": 333.96884
                                        }
                                    ]
                                },
                                "inferText": "1",
                                "inferConfidence": 0.9799099
                            }
                        ]
                    },
                    {
                        "name": "name",
                        "valueType": "ALL",
                        "boundingPoly": {
                            "vertices": [
                                {
                                    "x": 287.2125,
                                    "y": 287.2125
                                },
                                {
                                    "x": 380.86874,
                                    "y": 287.2125
                                },
                                {
                                    "x": 380.86874,
                                    "y": 328.8375
                                },
                                {
                                    "x": 287.2125,
                                    "y": 328.8375
                                }
                            ]
                        },
                        "inferText": "David",
                        "inferConfidence": 0.99630755,
                        "type": "NORMAL"
                    },
                    {
                        "name": "fax-checkbox",
                        "valueType": "ALL",
                        "boundingPoly": {
                            "vertices": [
                                {
                                    "x": 87.08151,
                                    "y": 736.90735
                                },
                                {
                                    "x": 140.0801,
                                    "y": 736.91125
                                },
                                {
                                    "x": 140.10016,
                                    "y": 791.9156
                                },
                                {
                                    "x": 87.101494,
                                    "y": 791.9121
                                }
                            ]
                        },
                        "inferText": "",
                        "inferConfidence": 0.99464625,
                        "type": "CHECKBOX",
                        "checked": true
                    }
                ]
            }
        ]
    }
    

    API 예제

    다음은 각 언어별 CLOVA OCR API 구현 예제입니다

    • Request with multipart/form-data
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.UUID;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class OCRGeneralAPIDemo {
    
    	public static void main(String[] args) {
    		String apiURL = "YOUR_API_URL";
    		String secretKey = "YOUR_SECRET_KEY";
    		String imageFile = "YOUR_IMAGE_FILE";
    
    		try {
    			URL url = new URL(apiURL);
    			HttpURLConnection con = (HttpURLConnection)url.openConnection();
    			con.setUseCaches(false);
    			con.setDoInput(true);
    			con.setDoOutput(true);
    			con.setReadTimeout(30000);
    			con.setRequestMethod("POST");
    			String boundary = "----" + UUID.randomUUID().toString().replaceAll("-", "");
    			con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    			con.setRequestProperty("X-OCR-SECRET", secretKey);
    
    			JSONObject json = new JSONObject();
    			json.put("version", "V2");
    			json.put("requestId", UUID.randomUUID().toString());
    			json.put("timestamp", System.currentTimeMillis());
    			JSONObject image = new JSONObject();
    			image.put("format", "jpg");
    			image.put("name", "demo");
    			JSONArray images = new JSONArray();
    			images.put(image);
    			json.put("images", images);
    			String postParams = json.toString();
    
    			con.connect();
    			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    			long start = System.currentTimeMillis();
    			File file = new File(imageFile);
    			writeMultiPart(wr, postParams, file, boundary);
    			wr.close();
    
    			int responseCode = con.getResponseCode();
    			BufferedReader br;
    			if (responseCode == 200) {
    				br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    			} else {
    				br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    			}
    			String inputLine;
    			StringBuffer response = new StringBuffer();
    			while ((inputLine = br.readLine()) != null) {
    				response.append(inputLine);
    			}
    			br.close();
    
    			System.out.println(response);
    		} catch (Exception e) {
    			System.out.println(e);
    		}
    	}
    
    	private static void writeMultiPart(OutputStream out, String jsonMessage, File file, String boundary) throws
    		IOException {
    		StringBuilder sb = new StringBuilder();
    		sb.append("--").append(boundary).append("\r\n");
    		sb.append("Content-Disposition:form-data; name=\"message\"\r\n\r\n");
    		sb.append(jsonMessage);
    		sb.append("\r\n");
    
    		out.write(sb.toString().getBytes("UTF-8"));
    		out.flush();
    
    		if (file != null && file.isFile()) {
    			out.write(("--" + boundary + "\r\n").getBytes("UTF-8"));
    			StringBuilder fileString = new StringBuilder();
    			fileString
    				.append("Content-Disposition:form-data; name=\"file\"; filename=");
    			fileString.append("\"" + file.getName() + "\"\r\n");
    			fileString.append("Content-Type: application/octet-stream\r\n\r\n");
    			out.write(fileString.toString().getBytes("UTF-8"));
    			out.flush();
    
    			try (FileInputStream fis = new FileInputStream(file)) {
    				byte[] buffer = new byte[8192];
    				int count;
    				while ((count = fis.read(buffer)) != -1) {
    					out.write(buffer, 0, count);
    				}
    				out.write("\r\n".getBytes());
    			}
    
    			out.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
    		}
    		out.flush();
    	}
    }
    
    import requests
    import uuid
    import time
    import json
    
    api_url = 'YOUR_API_URL'
    secret_key = 'YOUR_SECRET_KEY'
    image_file = 'YOUR_IMAGE_FILE'
    
    request_json = {
        'images': [
            {
                'format': 'jpg',
                'name': 'demo'
            }
        ],
        'requestId': str(uuid.uuid4()),
        'version': 'V2',
        'timestamp': int(round(time.time() * 1000))
    }
    
    payload = {'message': json.dumps(request_json).encode('UTF-8')}
    files = [
      ('file', open(image_file,'rb'))
    ]
    headers = {
      'X-OCR-SECRET': secret_key
    }
    
    response = requests.request("POST", api_url, headers=headers, data = payload, files = files)
    
    print(response.text.encode('utf8'))
    
    
    <?php
      $client_secret = "YOUR_SECRET_KEY";
      $url = "YOUR_API_URL";
      $image_file = "YOUR_IMAGE_FILE";
    
      $params->version = "V2";
      $params->requestId = uniqid();
      $params->timestamp = time();
      $image->format = "jpg";
      $image->name = "demo";
      $images = array($image);
      $params->images = $images;
      $json = json_encode($params);
      
      $boundary = uniqid();
      $is_post = true;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, $is_post);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $post_form = array("message" => $json, "file" => new CURLFILE($image_file));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_form);
      $headers = array();
      $headers[] = "X-OCR-SECRET: ".$client_secret;
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      $response = curl_exec($ch);
      $err = curl_error($ch);
      $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close ($ch);
    
      echo $status_code;
      if($status_code == 200) {
        echo $response;
      } else {
        echo "ERROR: ".$response;
      }
    ?>
    
    const FormData = require('form-data')
    const axios = require('axios')
    
    function requestWithBase64 () {
      axios
        .post(
          '', // APIGW Invoke URL
          {
            images: [
              {
                format: '', // file format
                name: '', // image name
                data: '' // image base64 string(only need part of data). Example: base64String.split(',')[1]
              }
            ],
            requestId: '', // unique string
            timestamp: 0,
            version: 'V2'
          },
          {
            headers: {
              'X-OCR-SECRET': '' // Secret Key 
            }
          }
        )
        .then(res => {
          if (res.status === 200) {
            console.log('requestWithBase64 response:', res.data)
          }
        })
        .catch(e => {
          console.warn('requestWithBase64 error', e.response)
        })
    }
    
    function requestWithFile () {
      const file = '' // image file object. Example: fs.createReadStream('./example.png')
      const message = {
        images: [
          {
            format: '', // file format
            name: '' // file name
          }
        ],
        requestId: '', // unique string
        timestamp: 0,
        version: 'V2'
      }
      const formData = new FormData()
    
      formData.append('file', file)
      formData.append('message', JSON.stringify(message))
    
      axios
        .post(
          '', // APIGW Invoke URL
          formData,
          {
            headers: {
              'X-OCR-SECRET': '', // Secret Key 
              ...formData.getHeaders()
            }
          }
        )
        .then(res => {
          if (res.status === 200) {
            console.log('requestWithFile response:', res.data)
          }
        })
        .catch(e => {
          console.warn('requestWithFile error', e.response)
        })
    }
    
    • Request with application/json
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.UUID;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class OCRGeneralAPIDemo {
    
    	public static void main(String[] args) {
    		String apiURL = "YOUR_API_URL";
    		String secretKey = "YOUR_SECRET_KEY";
    
    		try {
    			URL url = new URL(apiURL);
    			HttpURLConnection con = (HttpURLConnection)url.openConnection();
    			con.setUseCaches(false);
    			con.setDoInput(true);
    			con.setDoOutput(true);
    			con.setRequestMethod("POST");
    			con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    			con.setRequestProperty("X-OCR-SECRET", secretKey);
    
    			JSONObject json = new JSONObject();
    			json.put("version", "V2");
    			json.put("requestId", UUID.randomUUID().toString());
    			json.put("timestamp", System.currentTimeMillis());
    			JSONObject image = new JSONObject();
    			image.put("format", "jpg");
    			image.put("url", "https://kr.object.ncloudstorage.com/ocr-ci-test/sample/1.jpg"); // image should be public, otherwise, should use data
    			// FileInputStream inputStream = new FileInputStream("YOUR_IMAGE_FILE");
    			// byte[] buffer = new byte[inputStream.available()];
    			// inputStream.read(buffer);
    			// inputStream.close();
    			// image.put("data", buffer);
    			image.put("name", "demo");
    			JSONArray images = new JSONArray();
    			images.put(image);
    			json.put("images", images);
    			String postParams = json.toString();
    
    			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    			wr.writeBytes(postParams);
    			wr.flush();
    			wr.close();
    
    			int responseCode = con.getResponseCode();
    			BufferedReader br;
    			if (responseCode == 200) {
    				br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    			} else {
    				br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    			}
    			String inputLine;
    			StringBuffer response = new StringBuffer();
    			while ((inputLine = br.readLine()) != null) {
    				response.append(inputLine);
    			}
    			br.close();
    
    			System.out.println(response);
    		} catch (Exception e) {
    			System.out.println(e);
    		}
    	}
    
    }
    
    
    import requests
    import uuid
    import time
    import base64
    import json
    
    api_url = 'YOUR_API_URL'
    secret_key = 'YOUR_SECRET_KEY'
    image_url = 'YOUR_IMAGE_URL'
    # image_file = 'YOUR_IMAGE_FILE'
    # with open(image_file,'rb') as f:
    #     file_data = f.read()
    
    request_json = {
        'images': [
            {
                'format': 'jpg',
                'name': 'demo',
    #             'data': base64.b64encode(file_data).decode()
                'url': image_url
            }
        ],
        'requestId': str(uuid.uuid4()),
        'version': 'V2',
        'timestamp': int(round(time.time() * 1000))
    }
    
    payload = json.dumps(request_json).encode('UTF-8')
    headers = {
      'X-OCR-SECRET': secret_key,
      'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", api_url, headers=headers, data = payload)
    
    print(response.text)
    
    
    <?php
      $client_secret = "YOUR_SECRET_KEY";
      $url = "YOUR_API_URL";
      $image_url = "YOUR_IMAGE_URL";
      // $image_file = "YOUR_IMAGE_FILE";
    
      $params->version = "V2";
      $params->requestId = "uuid";
      $params->timestamp = time();
      $image->format = "jpg";
      $image->url = $image_url;
      // $image->data = base64_encode(file_get_contents($image_file));
      $image->name = "demo";
      $images = array($image);
      $params->images = $images;
      $json = json_encode($params);
    
      $is_post = true;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, $is_post);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
      $headers = array();
      $headers[] = "X-OCR-SECRET: ".$client_secret;
      $headers[] = "Content-Type:application/json; charset=utf-8";
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      $response = curl_exec($ch);
      $err = curl_error($ch);
      $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close ($ch);
    
      echo $status_code;
      if($status_code == 200) {
        echo $response;
      } else {
        echo "ERROR: ".$response;
      }
    ?>
    
    
    <%
    Function ASPPostJSON()
        Dim objXmlHttp
        Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
        url = "YOUR_INVOKE_URL"
        secret = "YOUR_SECRET_KEY"
        base64 = """"+ToBase64(getBinaryFile(Server.MapPath("test.jpg")))+""""
        body = "{""images"":[{""format"":""jpg"",""name"":""test 1"",""data"":"+base64+"}],""requestId"":""string"",""timestamp"":0,""version"":""V2"",""lang"":""ko""}"
        objXmlHttp.Open "POST", url, False
        objXmlHttp.SetRequestHeader "Content-Type", "application/json"
        objXmlHttp.SetRequestHeader "X-OCR-SECRET", secret
    
        objXmlHttp.Send body
    
        ASPPostJSON = CStr(objXmlHttp.ResponseText)
    
        Response.write(ASPPostJSON)
        Set objXmlHttp = Nothing
    
    End Function
    
    Function getBinaryFile(strFilePath)
      Dim TypeBinary, oStream
    
      TypeBinary = 1
    
      Set oStream = Server.CreateObject("ADODB.Stream")
    
      oStream.Open
    
      oStream.Type = TypeBinary
      oStream.LoadFromFile strFilePath
    
      getBinaryFile = oStream.read
    
      Set oStream = Nothing
    
    End Function
    
    Function ToBase64(rabyt)
    
         Dim xml: Set xml = CreateObject("MSXML2.DOMDocument.3.0")
         xml.LoadXml "<root />"
         xml.documentElement.dataType = "bin.base64"
         xml.documentElement.nodeTypedValue = rabyt
    
         ToBase64 = xml.documentElement.Text
    
    End Function
    
    call ASPPostJSON()
    %>
    

    Error code

    HttpStatusCodeDescription
    400Request parameters invalid or constraint problem.
    401Api secret(X-CHATBOT-API-KEY) wrong
    500Internal server error

    Error Response Body:

    {
      "code": "Error Code",
      "message": "error details message.",
      "path": "request API path",
      "timestamp": 1570776853475
    }
    
    ErrorCodeDescription
    0001URL is invalid.
    0002Secret key validate failed.
    0011Request body invalid.
    0021Protocol version not support.
    0022Request domain invalid.
    0023API request count reach the upper limit.
    0025Calls to this api have exceeded the rate limit.
    0500Unknown service error.
    0501OCR Service error.
    1021Not found deploy infomation. Please confirm the template is released.

    이 문서가 도움이 되었습니까?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.