Updated on 2024-06-13 GMT+08:00

Python SDK

This section describes how to use the new Python SDK to quickly develop OCR services.

Prerequisites

  • You have registered a Huawei ID and enabled Huawei Cloud services. Your account cannot be in arrears or frozen.
  • Python 3 or later is available.
  • You have obtained an AK and an SK on the My Credentials > Access Keys page. The AK and SK are contained in the credentials.csv file.
    Figure 1 Creating an access key

  • You have obtained the IAM user name, account name, and the project ID of your target region on the My Credentials > API Credentials page. The information will be used during service calling. Save it in advance.
    Figure 2 API Credentials

Installing the SDK

Python 3 or later is supported. Run the python --version command to check the current Python version.

Before you use the SDK, install huaweicloudsdkcore and huaweicloudsdkocr in either of the following ways:

  • Using pip
    # If the message "Successfully installed xxx" is displayed, the installation is successful.
    # Install the core library.
    pip install huaweicloudsdkcore
    # Install the OCR service library.
    pip install huaweicloudsdkocr
  • Using the source code
    The SDK version can be queried from SDK Center.
    # Install the core library.
    cd huaweicloudsdkcore-${version}
    python setup.py install
    
    # Install the OCR service library.
    cd huaweicloudsdkocr-${version}
    python setup.py install

Getting Started

  1. Import dependency modules.
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkcore.http.http_config import HttpConfig
    # Import the huaweicloudsdk{service} library of a specified cloud service.
    from huaweicloudsdkocr.v1.region.ocr_region import OcrRegion
    from huaweicloudsdkocr.v1 import *
  2. Configure client connection parameters.
    • Using the default configuration
      # Use the default configuration. If the error message "'HttpConfig' is not defined" is displayed, check whether the SDK is installed correctly.
      config = HttpConfig.get_default_config()
    • (Optional) Configuring a network proxy
      # Configure network proxy as needed.
      config.proxy_protocol = 'http'
      config.proxy_host = 'proxy.huaweicloud.com'
      config.proxy_port = 80
      config.proxy_user = 'username'
      config.proxy_password = 'password'
    • (Optional) Configuring the timeout
      # The default connection timeout interval is 60 seconds, and the read timeout interval is 120 seconds. You can set timeout to timeout or (connect timeout, read timeout).
      config.timeout = 120
    • (Optional) Configuring an SSL
      # Configure whether to skip SSL certificate verification as required.
      config.ignore_ssl_verification = True
      # Configure the server CA certificate so that the SDK can verify the server certificate.
      config.ssl_ca_cert = ssl_ca_cert

    After the client connection parameters are configured, you need to configure the code corresponding to with_http_config(config) in the initialized client. For details, see the code following client in 4.

  3. Configure authentication information.

    Configure ak, sk, and project_id. AK is used together with SK to sign requests cryptographically, ensuring that the requests are secret, complete, and correct. There are two authentication methods:

    • Initialize authentication information.
      ak = os.environ.get("HUAWEICLOUD_SDK_AK")
      sk = os.environ.get("HUAWEICLOUD_SDK_SK")
      • Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
      • In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
    • Using a permanent AK and SK
      credentials = BasicCredentials(ak, sk, project_id)
    • Using a temporary AK and SK
      credentials = BasicCredentials(ak, sk, project_id).with_security_token(security_token)

    The authentication parameters are described as follows:

    • ak and sk: access key and secrete access key. For details about how to obtain them, see Prerequisites.
    • project_id: Huawei Cloud project ID. For details about how to obtain the ID, see Prerequisites.
    • security_token: security token used for temporary AK/SK authentication. It can be obtained through a token or an agency.
  4. Initialize the client (using either of the following methods).
    • (Recommended) Specifying a region
      # Add the region dependency.
      from huaweicloudsdkocr.v1.region.ocr_region import OcrRegion
      
      # Initialize the client {Service}Client of a specified cloud service. The following uses OcrClient of OCR as an example.
      client = OcrClient.new_builder() \
          .with_http_config(config) \
          .with_credentials(credentials) \
          .with_region(OcrRegion.value_of("ap-southeast-2")) \
          .build()
    • Specifying an endpoint for a cloud service
      # Specify the endpoint for OCR, for example, AP-Bangkok.
      endpoint = "https://ocr.ap-southeast-2.myhuaweicloud.com"
      
      
      # Initialize the client {Service}Client of a specified cloud service. The following uses OcrClient of OCR as an example.
      client = OcrClient.new_builder() \
          .with_http_config(config) \
          .with_credentials(credentials) \
          .with_endpoint(endpoint) \
          .build()

      endpoint indicates the endpoints for Huawei Cloud services. For details, see Regions and Endpoints.

  5. Send a request and check the response.
    # The following uses calling the RecognizePassport API of Passport OCR as an example.
    request = RecognizePassportRequest()
    request.body = PassportRequestBody(
        url="Image URL"
    )
    response = client.recognize_passport(request)
    print(response)
  6. Handle exceptions.
    Table 1 Exception handling

    Level-1 Category

    Level-1 Category Description

    Level-2 Category

    Level-2 Category Description

    ConnectionException

    Connection exception

    HostUnreachableException

    The network is unreachable or access is rejected.

    SslHandShakeException

    SSL authentication is abnormal.

    RequestTimeoutException

    Response timeout exception

    CallTimeoutException

    The server fails to respond to a single request before timeout.

    RetryOutageException

    No valid response is returned after the maximum number of retries specified in the retry policy is reached.

    ServiceResponseException

    Server response exception

    ServerResponseException

    Internal server error. HTTP response code: [500,].

    ClientRequestException

    Invalid request parameter. HTTP response code: [400, 500).

    # Troubleshooting
    try:
        request = RecognizePassportRequest()
        response = client.recognize_passport(request)
        print(response)
    except exceptions.ClientResponseException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

For details about how to use the asynchronous client and configure logs, see SDK Center and Python SDK Usage Guide.

Automatic Generation of Sample Code

API Explorer allows for API search and platform debugging, with features such as quick and comprehensive search, visual debugging, access to help documentation, and online consultation.

You only need to modify API parameters in the API Explorer to automatically generate the corresponding sample code.

Figure 3 API Explorer