SDK overview
This topic introduces the SDKs for popular programming languages and provides usage examples.
SDK
The Optical Character Recognition (OCR) SDK encapsulates all APIs from the 2021-07-07 version. It authenticates callers using an AccessKey and automatically handles tasks like signature generation. This simplifies the development process, reduces errors, and improves code maintainability.
Alibaba Cloud Developer Center provides SDKs for popular programming languages, along with repository links, installation commands, and release notes. For more information, visit the Developer Center.
Prerequisites
-
Enable service: First, sign up for or log in to your Alibaba Cloud account. Then, go to the Optical Character Recognition (OCR) console to enable the services you need. The Optical Character Recognition (OCR) product offers 10 types of OCR services. Each service must be enabled separately. No fees are incurred when you enable a service.
Depending on the service you enable, you receive a monthly free quota of 200 calls or a one-time free quota of 50 calls. Each successful API call consumes one call from your free quota. After the free quota is used up, you are charged based on your usage.
-
Obtain an access credential: You must obtain an AccessKey before you install and use the SDK.
-
Hover over your account avatar in the upper-right corner of the console and click AccessKey.
-
On the AccessKey page, view your AccessKey details.
The AccessKey list includes columns such as AccessKey ID, Status, Creation Time, and Actions. In the Status column, you can check whether an AccessKey is enabled or disabled.
If the AccessKey list is empty or contains no enabled AccessKeys, create an AccessKey.
If you are using a RAM user for API calls, ensure the user has the AliyunOCRFullAccess permission. Otherwise, calls to the Alibaba Cloud Optical Character Recognition (OCR) service will fail.
-
Code examples
This example shows how to integrate the SDK and call the unified recognition API to recognize text from an ID card. To recognize text from other types of documents, you only need to specify the image type using the Type parameter. You do not need to switch to a different API. For more information, see Details for the Type parameter.
Programming languages
Select your preferred language to call the Optical Character Recognition (OCR) API.
Java
Step 1: Configure Java environment
Step 2: Call the OCR API
Run the following code to call the Optical Character Recognition (OCR) API:
import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponse;
import com.aliyun.tea.*;
public class Sample {
public static com.aliyun.ocr_api20210707.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
return new com.aliyun.ocr_api20210707.Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.ocr_api20210707.Client client = Sample.createClient();
com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest recognizeAllTextRequest = new com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest()
.setUrl("https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg")
.setType("IdCard");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
RecognizeAllTextResponse resp = client.recognizeAllTextWithOptions(recognizeAllTextRequest, runtime);
System.out.println(com.aliyun.teautil.Common.toJSONString(resp.body.data));
} catch (TeaException error) {
// For demonstration purposes only. In your project, handle exceptions carefully and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// For demonstration purposes only. In your project, handle exceptions carefully and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Python
Step 1: Configure Python environment
Virtual environment (optional)
Step 2: Call the OCR API
You can create a new Python file, name it hello_ocr.py, copy the following code into hello_ocr.py, and save it.
# -*- coding: utf-8 -*-
import os
import sys
from typing import List
from alibabacloud_ocr_api20210707.client import Client as ocr_api20210707Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ocr_api20210707 import models as ocr_api_20210707_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> ocr_api20210707Client:
config = open_api_models.Config(
# Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
config.endpoint = f'ocr-api.cn-hangzhou.aliyuncs.com'
return ocr_api20210707Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = Sample.create_client()
recognize_all_text_request = ocr_api_20210707_models.RecognizeAllTextRequest(
url='https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg',
type='IdCard'
)
runtime = util_models.RuntimeOptions()
try:
resp = client.recognize_all_text_with_options(recognize_all_text_request, runtime)
print(resp.body.data)
except Exception as error:
# For demonstration purposes only. In your project, handle exceptions carefully and do not ignore them.
# Error message
print(error.message)
# Diagnostic address
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client()
recognize_all_text_request = ocr_api_20210707_models.RecognizeAllTextRequest(
url='https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg',
type='IdCard'
)
runtime = util_models.RuntimeOptions()
try:
# The result of this asynchronous call is not printed. To see the output, assign the awaited result to a variable and print it.
await client.recognize_all_text_with_options_async(recognize_all_text_request, runtime)
except Exception as error:
# For demonstration purposes only. In your project, handle exceptions carefully and do not ignore them.
# Error message
print(error.message)
# Diagnostic address
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
if __name__ == '__main__':
Sample.main(sys.argv[1:])
Go
Step 1: Configure Go environment
Step 2: Call the OCR API
You can create a new Go file named hello_ocr.go, copy the following code into hello_ocr.go, and save the file.
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
ocr_api20210707 "github.com/alibabacloud-go/ocr-api-20210707/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"os"
"strings"
)
func CreateClient() (_result *ocr_api20210707.Client, _err error) {
config := &openapi.Config{
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
config.Endpoint = tea.String("ocr-api.cn-hangzhou.aliyuncs.com")
_result = &ocr_api20210707.Client{}
_result, _err = ocr_api20210707.NewClient(config)
return _result, _err
}
func _main(args []*string) (_err error) {
client, _err := CreateClient()
if _err != nil {
return _err
}
recognizeAllTextRequest := &ocr_api20210707.RecognizeAllTextRequest{
Url: tea.String("https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg"),
Type: tea.String("IdCard"),
}
runtime := &util.RuntimeOptions{}
tryErr := func() (_e error) {
defer func() {
if r := tea.Recover(recover()); r != nil {
_e = r
}
}()
resp, _err := client.RecognizeAllTextWithOptions(recognizeAllTextRequest, runtime)
if _err != nil {
return _err
}
fmt.Println(resp.Body.Data)
return nil
}()
if tryErr != nil {
var error = &tea.SDKError{}
if _t, ok := tryErr.(*tea.SDKError); ok {
error = _t
} else {
error.Message = tea.String(tryErr.Error())
}
// For demonstration purposes only. In your project, handle exceptions carefully and do not ignore them.
// Error message
fmt.Println(tea.StringValue(error.Message))
// Diagnostic address
var data interface{}
d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
d.Decode(&data)
if m, ok := data.(map[string]interface{}); ok {
recommend, _ := m["Recommend"]
fmt.Println(recommend)
}
_, _err = util.AssertAsString(error.Message)
if _err != nil {
return _err
}
}
return _err
}
func main() {
err := _main(tea.StringSlice(os.Args[1:]))
if err != nil {
panic(err)
}
}