CLOVA OCR Custom API
- 印刷する
- PDF
CLOVA OCR Custom API
- 印刷する
- PDF
Article Summary
Share feedback
Thanks for sharing your feedback!
version
Version | Date | Changes |
---|---|---|
v1.0.0 | 2019-12-05 | 初回作成 |
v1.0.1 | 2020-02-21 | General API呼び出しのレスポンスに boundingPoly情報を提供 |
v2.0.0 | 2020-03-26 | CLOVA OCRプレミアムモデルの提供により、マルチボックス、チェックボックス認識機能を追加 リクエストバージョンに応じて(V1/V2)認識結果として bounding/boundingPoly情報を提供 V2の使用を推奨し、V2を使用すると boundingPoly情報を提供 |
v2.0.1 | 2021-01-21 | General API JSON改行情報を提供 Delete subFiled in ImageField object |
v2.0.2 | 2021-02-04 | Recognition Results Object内に convertedImageInfoフィールドを追加 |
v2.0.3 | 2021-05-27 | combineResultフィールド and lineBreak apiを追加 |
v2.0.4 | 2021-07-22 | zh-TW言語対応 |
v2.0.5 | 2021-09-16 | 表の抽出機能を追加 |
v2.0.6 | 2023-02-23 | 多言語選択機能を追加 |
リクエスト
Method | Request URI |
---|---|
POST | CLOVA OCRビルダーから作成された API Gatewayの InvokeURLで呼び出し 各ドメインごとに固有の呼び出し URLが作成される |
- TEXT OCR認識と Template OCR認識をリクエスト
区分 | 説明 | Path | Request | Response |
---|---|---|---|---|
TEXT OCR | テンプレートの定義なしで画像のすべてのテキストを認識 | /general | 画像認識リクエストの形式に従う | 画像認識結果の形式に従う matchedTemplate、title and validationResult値は伝達されない |
Template OCR | ドメインにリリースされたテンプレートが含まれている画像を認識 | /infer | 画像認識リクエストの形式に従う | 画像認識結果の形式に従う |
リクエストヘッダ
ヘッダ名 | 説明 |
---|---|
X-OCR-SECRET | ドメインで API Gateway連携時に作成した X-OCR-SECRET:{Client Secret} |
Content-Type | application/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
- 画像認識リクエスト
区分 | Json Model |
---|---|
画像認識リクエスト | { "version": "string", "requestId": "string", "timestamp": 0, "lang": "string", "images": [{ "format": "string", "url": "string", "data": "string", "name": "string", "templateIds": [ 0 ] }], "enableTableDetection": true } |
画像認識リクエストフィールドの詳細説明
フィールド名 | 必須有無 | タイプ | 説明 | 制限事項 |
---|---|---|---|---|
version | Yes | string | バージョン情報は必須入力項目で、V1か V2と入力 V2の使用を推奨し、V2を使用すると boundingPoly情報を提供 | |
requestId | Yes | string | API呼び出し UUID | |
timestamp | Yes | 0 | API呼び出し Timestamp | |
lang | No | string | OCR認識時にリクエストする言語情報 | 設定可能な言語値は「ko」/「ja」/「zh-TW」 であり、langフィールドが設定されていない場合、ドメインの言語設定値が設定値なく defaultに設定される。コンマ(,)で複数の言語を呼び出しできます。(例: 「ko,ja,zh-TW」) |
images | Yes | string | Json arrayで入力され、現在は1つの画像のみ許可(韓国語/日本語) | General OCRは50MB、Template OCRは20MB(pdf、tiffは50MB)までサポート |
images.format | Yes | string | 画像フォーマットを設定 | 「jpg」、「jpeg」、「png」、「pdf」、「tiff」画像フォーマットに対応。General OCR: 最大10ページの pdf認識をサポート、Template OCR: 最大5ページの pdf/tiff認識をサポート |
images.url | No | string | images.urlもしくは images.dataのうち1つが存在する必要がある | URLは、画像を取り入れることができる公開 URLである必要がある |
images.data | No | string | images.urlもしくは images.dataのうち1つが存在する必要がある(URLとデータの両方が存在する場合はデータを使用し、URLは無視) | images.dataは base64エンコード画像バイト |
images.name | Yes | string | 画像名入力 画像の識別やレスポンス結果の確認に使用 | |
images.templateIds | No | json array | テキスト OCR APIでは使用されない Template OCR APIでは、このフィールドを設定しないとドメインにリリースされたすべてのサービステンプレートに自動分類される | |
enableTableDetection | No | Boolean | 文書内の表(Table)領域を自動認識して文字(Text)とともに構造化された形で提供。 | General OCRのみサポート |
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
- Image Recognition Request
KEY | Required | VALUE |
---|---|---|
message | Y | {"version": "string","requestId": "string","timestamp": 0,"lang": "string","images": [{ "format": "string", "name": "string", "templateIds": [ 0 ] }]} |
file | Y | image file steam data |
Form Data Message Value Description
Field name | Required | Type | Description | Constraints |
---|---|---|---|---|
version | Yes | string | バージョン情報は必須入力項目で、V1か V2と入力 | V2の使用を推奨し、V2を使用すると boundingPoly情報を提供 |
requestId | Yes | string | API呼び出し UUID | |
timestamp | Yes | integer | API呼び出し Timestamp値 | |
lang | No | string | OCR認識時にリクエストする言語情報 | 設定可能な言語は「ko」、「ja」、「zh-TW」で、langフィールドが設定されていない場合、ドメインの言語はデフォルトに設定 Use comma(,) in multi-language.ex:"ko,ja,zh-TW" |
images | Yes | string | It is entered as Json array and currently only one image input is allowed (Korean/Japanese) | General OCRは50MB、Template OCRは20MB(pdf、tiffは50MB)までサポート |
images.format | Yes | string | 画像フォーマットを設定 | 「jpg」、「jpeg」、「png」、「pdf」、「tiff」画像フォーマットに対応。General OCR: 最大10ページの pdf認識をサポート、Template OCR: 最大5ページの pdf/tiff認識をサポート |
images.name | Yes | string | 画像名を入力。画像の識別やレスポンス結果の確認に使用 | |
images.templateIds | No | json array | テキスト OCR APIでは使用されない Template OCR APIでは、このフィールドを設定しないとドメインにリリースされたすべてのサービステンプレートに自動分類される | |
enableTableDetection | No | Boolean | 文書内の表(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'
- 画像認識結果
区分 | Json Model |
---|---|
画像認識結果 | { "uid": "string", "name": "string", "inferResult": "string", "message": "string", "matchedTemplate": { "id": 0, "name": "string" }, "title": {}, "fields": [ {} ], "validationResult": { "result": "string", "message": "string"} } |
画像認識結果フィールドの詳細説明
フィールド名 | データタイプ | 説明 |
---|---|---|
uid | string | APIの有効性を検査するために提供される固有 IDで、有効性検査リクエストを追跡ために使用 |
name | string | リクエストした画像名 |
inferResult | string | - 画像推論結果 「SUCCESS」: 画像認識成功 「FAILURE」: 画像認識失敗 「ERROR」: Image recognition exception。 |
message | string | 画像認識成功時「SUCCESS」 画像認識失敗の場合、エラーメッセージが表示される エラーメッセージは下段で詳しくご案内 |
matchedTemplate | json object | 画像認識に一致したテンプレート情報でテンプレート IDと名前を含む 推論が失敗または一致するテンプレートが見つからない場合は、このフィールドにレスポンスしない |
matchedTemplate.id | 0 | テンプレート ID |
matchedTemplate.name | string | テンプレートの名前 |
title | string | 画像のタイトル |
fields | Json array object | ImageFieldオブジェクトを参照 |
validationResult | json object | 有効性チェックの結果 |
validationResult.result | string | - 結果コード 「NO_REQUESTED」: 検証タスクが実行されていない 「UNCHECKED」: 動作レスポンスが確認されていないか、レスポンスが受け入れられていない 「ERROR」: 検証実行にエラーが発生 「VALID」: 検証結果が有効 「INVALID」: 検証結果が有効でない 「UNCHECHED」、「ERROR」および「INVALID」は有効性検証の失敗と表示される |
validationResult.message | string | Validationの詳細メッセージで、常にレスポンスを受ける値ではない |
combineResult | json object | 判読結果の結合 |
combineResult.name | string | 結合フィールド名 |
combineResult.text | string | フィールド別の出力値+固定 TEXT |
- ImageFieldオブジェクト
区分 | Json Model |
---|---|
Image Field | { "name": "string", "valueType": "string", "inferText": "string", "inferConfidence": 0.0, "bounding": {} } |
ImageFieldオブジェクトフィールドの詳細説明
フィールド名 | データタイプ | 説明 |
---|---|---|
name | string | 画像名 |
valueType | string | 常にリターンされる値ではなく、フィールドのテキスト値タイプ "ALL": テキストと数字 |
inferText | string | 認識結果のテキスト |
inferConfidence | 0.0 | 類推された結果に対する確信。0-1の間の値が大きいほどより正確 |
bounding | boundingオブジェクト | boundingオブジェクトを参照 |
- boundingオブジェクト
区分 | Json Model |
---|---|
bounding | { "top": 0.0, "left": 0.0, "width": 0.0, "height": 0.0 } |
boundingオブジェクトフィールドの詳細説明
フィールド名 | データタイプ | 説明 |
---|---|---|
top | 0.0 | Bounding Y座標 |
left | 0.0 | Bounding X座標 |
width | 0.0 | Bounding width. |
height | 0.0 | Bounding height. |
V2レスポンスボディ
Request version is 'V2'
- Image Recognition Results
Classification | Json 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 Name | Data Type | Description |
---|---|---|
uid | string | A unique ID that is provided to validate the API, which is used to track validation requests. |
name | string | The requested image name. |
inferResult | string | Image inference result. "SUCCESS": Image recognition successful. "FAILURE": Image recognition failed."ERROR": Image recognition exception.No charge when ERROR. |
message | string | Successful image recognition, "SUCCESS" If image recognition fails, an error message is displayed. Error messages are detailed at the bottom |
matchedTemplate | json object | Include 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.id | integer | Template ID. |
matchedTemplate.name | string | Name of the template. |
title | json object | ImageField Object Reference |
fields | Json array object | ImageField Object Reference |
validationResult | json object | Validation result. |
validationResult.result | string | Result 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.message | string | It is not always the value that is returned in the Validation detail message. |
convertedImageInfo | json object | Only response when image format is pdf/tiff. Coordinates are based on converted image when request format is pdf/tiff. |
convertedImageInfo.width | integer | The base image width. |
convertedImageInfo.height | integer | The base image height. |
convertedImageInfo.pageIndex | integer | The page index of pdf/tiff. |
combineResult | json object | 判読結果の結合 |
combineResult.name | string | 結合フィールド名 |
combineResult.text | string | フィールド別の出力値+固定 TEXT |
tables | Json array object | ImageTable Object Reference |
- ImageField object
Classification | Json 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 Name | Data Type | Description |
---|---|---|
name | string | Image name. |
valueType | string | It is the text value type of the field. "ALL": text and numbers "NUMERIC":numbers |
inferText | string | Recognition Result Text When type is checkbox , it will be replaced by the return value in the setting |
inferConfidence | float | Confidence of infer result. Larger values of 0-1 are more accurate. |
boundingPoly | boundingPoly Object | boundingPoly Object reference |
type | string | - NORMAL - MULTI_BOX - CHECKBOX |
checked | boolean | Only 'CHECKBOX' type supported. Whether the field is checked or not. |
lineBreak | boolean | Only response in GENERAL api. Whether there is a newline after the text |
subFields | Json Array | Only response in Template api. SubField Object reference |
- boundingPoly object
Classification | Json Model |
---|---|
boundingPoly | { "vertices":[{}] } |
boundingPoly Object Field Details
Field Name | Data Type | Description |
---|---|---|
vertices | vertices object | vertices object reference |
- vertices object
Classification | Json Model |
---|---|
vertices | { "x": 0.0, "y": 0.0 } |
vertices Object Field Details
Field Name | Data Type | Description |
---|---|---|
x | float | X coodinate |
y | float | y coodinate |
- SubField Object
Classification | Json Model |
---|---|
subField | { "boundingPoly": {}, "inferText": "string", "inferConfidence":0.0 "lineBreak": false } |
subField Object Field Details
Field Name | Data Type | Description |
---|---|---|
boundingPoly | boundingPoly Object | boundingPoly Object reference |
inferText | string | Recognition Result Text |
inferConfidence | float | Confidence of infer result. Larger values of 0-1 are more accurate. |
lineBreak | boolean | Whether there is a newline after the text |
- ImageTable Object
Classification | Json Model |
---|---|
subField | { "cells": [], "boundingPoly": {}, "inferConfidence":0.0 } |
ImageTable Object Field Details
Field Name | Data Type | Description |
---|---|---|
boundingPoly | boundingPoly Object | boundingPoly Object reference |
cells | json array object | TableCell Object reference |
inferConfidence | float | Confidence of infer result. Larger values of 0-1 are more accurate. |
- TableCell Object
Classification | Json Model |
---|---|
subField | { "cellTextLines": [], "boundingPoly": {}, "inferConfidence":0.0, "rowSpan":0, "rowIndex":0, "columnSpan":0, "columnIndex":0 } |
TableCell Object Field Details
Field Name | Data Type | Description |
---|---|---|
boundingPoly | boundingPoly Object | boundingPoly Object reference |
cellTextLines | json array object | The lines in a cell. CellTextLine Object reference. |
inferConfidence | float | Confidence of infer result. Larger values of 0-1 are more accurate. |
rowSpan | int | The rowSpan property specifies the number of rows a cell should span. |
rowIndex | int | The rowIndex property specifies the position of a row in the rows collection of a table. |
columnSpan | int | The columnSpan property specifies how many columns an element should span across. |
columnIndex | int | The columnIndex property specifies the position of a column in the columns collection of a table. |
- CellTextLine Object
Classification | Json Model |
---|---|
subField | { "cellWords": [], "boundingPoly": {}, "inferConfidence":0.0 } |
CellTextLine Object Field Details
Field Name | Data Type | Description |
---|---|---|
boundingPoly | boundingPoly Object | boundingPoly Object reference |
inferConfidence | float | Confidence of infer result. Larger values of 0-1 are more accurate. |
cellWords | json array object | The words in a line. CellWord Object reference. |
- CellWord Object
Classification | Json Model |
---|---|
subField | { "inferText": "", "boundingPoly": {}, "inferConfidence":0.0 } |
CellWord Object Field Details
Field Name | Data Type | Description |
---|---|---|
boundingPoly | boundingPoly Object | boundingPoly Object reference |
inferConfidence | float | Confidence of infer result. Larger values of 0-1 are more accurate. |
inferText | string | 認識結果のテキスト |
例
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
HttpStatusCode | Description |
---|---|
400 | Request parameters invalid or constraint problem. |
401 | Api secret(X-CHATBOT-API-KEY) wrong |
500 | Internal server error |
Error Response Body:
{
"code": "Error Code",
"message": "error details message.",
"path": "request API path",
"timestamp": 1570776853475
}
ErrorCode | Description |
---|---|
0001 | URL is invalid. |
0002 | Secret key validate failed. |
0011 | Request body invalid. |
0021 | Protocol version not support. |
0022 | Request domain invalid. |
0023 | API request count reach the upper limit. |
0025 | Calls to this api have exceeded the rate limit. |
0500 | Unknown service error. |
0501 | OCR Service error. |
1021 | Not found deploy infomation. Please confirm the template is released. |
この記事は役に立ちましたか?