Python

更新时间:
复制 MD 格式

This topic shows you how to obtain, install, and use the Python SDK for Alibaba Cloud Vision Intelligence Platform services and provides code examples to get you started.

Note

For inquiries about SDK integration, API usage, or other issues related to the AI capabilities of the Alibaba Cloud Vision Intelligence Platform, contact us by joining the DingTalk group (ID: 23109592).

This SDK requires Python 3 or later. If your environment does not meet this requirement, upgrade your Python version.

Prerequisites

Before you use the Alibaba Cloud SDK, ensure that you have an Alibaba Cloud account and have created an AccessKey. For more information, see Create an AccessKey.

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.

  • Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.

  • Configure environment variables on Linux and macOS

    1. Open a terminal in IntelliJ IDEA.

    2. Run the following commands to configure the environment variables.

      Replace <access_key_id> with the AccessKey ID of your RAM user and <access_key_secret> with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Configure environment variables on Windows

    Create a new environment variable file, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. Restart the Windows operating system for the configurations to take effect.

Code examples

This topic uses RecognizeBankCard as an example.

File in an OSS bucket in the same region

Note

For more information about the endpoints for each capability category and the regions where the capabilities are available, see Endpoints.

# -*- coding: utf-8 -*-
# 1. This example uses the `RecognizeBankCard` capability from the optical character recognition category. 
# To use another capability, you must import the package and classes for the corresponding category. 
# You can find package names in this topic. The capability name is specified by the `Action` parameter in the API reference for the capability.
# For example, to use the `SegmentCommonImage` capability, you can find in its API reference that it belongs to the image segmentation category (`imageseg20191230`).
# Therefore, you need to change `alibabacloud_ocr20191230` to `alibabacloud_imageseg20191230` and `RecognizeBankCard` to `SegmentCommonImage`.
from alibabacloud_ocr20191230.client import Client
from alibabacloud_ocr20191230.models import RecognizeBankCardRequest
from alibabacloud_tea_util.models import RuntimeOptions
from alibabacloud_tea_openapi.models import Config

'''Bank card recognition example'''
# Initialize Config.
config = Config(
  # 2. To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
  # If you use the AccessKey of a RAM user, you must grant the `AliyunVIAPIFullAccess` permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
  # This example reads the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before you run this code.
  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
  # 3. The endpoint of the service. You must change this to the endpoint for the corresponding capability category. For more information, see https://help.aliyun.com/document_detail/143103.html.
  endpoint='ocr.cn-shanghai.aliyuncs.com',
  # The region ID of the endpoint.
  region_id='cn-shanghai'
)

# 4. Initialize the request. This example uses `RecognizeBankCardRequest`. For other capabilities, use the corresponding request class.
request = RecognizeBankCardRequest(image_url='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg')
# Initialize RuntimeObject.
runtime_option = RuntimeOptions()

try:
  # Initialize the client.
  client = Client(config)

  # 5. Call the API. The method name must be changed to the one that corresponds to the capability you are calling. 
  # The method name is generated based on the capability name. For example, if the capability name is `SegmentCommonImage`, the corresponding method name is `segment_common_image_with_options`.
  response = client.recognize_bank_card_with_options(request, runtime_option)
  # Get the complete response.
  print(response.body)
  # Get a specific field. This is only an example. For the fields of a specific capability, see the API reference for that capability.
  print(response.body.data.card_number)
  # Tip: You can call `response.body.__dict__` to view attribute names.
except Exception as error:
  # Get the complete error message.
  print(error)
  # Get a specific field.
  print(error.code)
  # Tip: You can call `error.__dict__` to view attribute names.
Note

All required changes are specified in the code comments. The following provides a summary:

  1. When you import packages, import the package and related classes for the target capability category. You can find package names in the Prerequisites section. The capability name is specified by the Action parameter in the API reference.

    For example, to use the SegmentCommonImage capability, you can find in the SegmentCommonImage API reference that this capability belongs to the image segmentation category (imageseg20191230) and its name is SegmentCommonImage. You need to change ocr20191230 in the code to imageseg20191230 and RecognizeBankCard to SegmentCommonImage.

  2. You must change the endpoint to the one for the correct capability category. If the endpoint does not match the category, an InvalidAction.NotFound error is returned. For more information about endpoints, see Endpoints.

  3. The request must use the package and class of the corresponding capability.

  4. The client method name must match the capability that you are calling. The method name is generated based on the capability name. For example, if the capability name is SegmentCommonImage, the corresponding method name is segment_common_image_with_options.

Local file or cross-region OSS file

Important

To process a local file or an OSS file from a different region, use an xxxAdvanceRequest object. The file is passed as a stream to the image_urlobject parameter.

# -*- coding: utf-8 -*-
# 1. This example uses the `RecognizeBankCard` capability from the optical character recognition category. 
# To use another capability, you must import the package and classes for the corresponding category. 
# You can find package names in this topic. The capability name is specified by the `Action` parameter in the API reference for the capability.
# For example, to use the `SegmentCommonImage` capability, you can find in its API reference that it belongs to the image segmentation category (`imageseg20191230`).
# Therefore, you need to change `alibabacloud_ocr20191230` to `alibabacloud_imageseg20191230` and `RecognizeBankCard` to `SegmentCommonImage`.
from alibabacloud_ocr20191230.client import Client
from alibabacloud_ocr20191230.models import RecognizeBankCardAdvanceRequest
from alibabacloud_tea_util.models import RuntimeOptions
from alibabacloud_tea_openapi.models import Config
from urllib.request import urlopen
import io

'''Bank card recognition example'''
# Initialize Config.
config = Config(
  # 2. To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
  # If you use the AccessKey of a RAM user, you must grant the `AliyunVIAPIFullAccess` permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
  # This example reads the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before you run this code.
  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
  # 3. The endpoint of the service. You must change this to the endpoint for the corresponding capability category. For more information, see https://help.aliyun.com/document_detail/143103.html.
  endpoint='ocr.cn-shanghai.aliyuncs.com',
  # The region ID of the endpoint.
  region_id='cn-shanghai'
)

# Initialize RuntimeObject.
runtime_option = RuntimeOptions()

try:
  # Scenario 1: Local file.
  # img = open(r'/tmp/bankCard.png', 'rb')
  # Remember to call img.close() to close the stream when you are done.
  # Scenario 2: Any accessible URL.
  url = 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg'
  img = io.BytesIO(urlopen(url).read())
  # 4. Initialize the request. This example uses `RecognizeBankCard`. For other capabilities, use the corresponding request class.
  request = RecognizeBankCardAdvanceRequest()
  request.image_urlobject = img
  # Initialize the client.
  client = Client(config)
  # 5. Call the API. The method name must be changed to the one that corresponds to the capability you are calling. 
  # The method name is generated based on the capability name. For example, if the capability name is `SegmentCommonImage`, the corresponding method name is `segment_common_image_advance`.
  response = client.recognize_bank_card_advance(request, runtime_option)
  # Get the complete response.
  print(response.body)
  # Get a specific field. This is only an example. For the fields of a specific capability, see the API reference for that capability.
  print(response.body.data.card_number)
  # Tip: You can call `response.body.__dict__` to view attribute names.
except Exception as error:
  # Get the complete error message.
  print(error)
  # Get a specific field.
  print(error.code)
  # Tip: You can call `error.__dict__` to view attribute names.
Note

All required changes are specified in the code comments. The following provides a summary:

  1. When you import packages, import the package and related classes for the target capability category. You can find package names in the Prerequisites section. The capability name is specified by the Action parameter in the API reference.

    For example, to use the SegmentCommonImage capability, you can find in the SegmentCommonImage API reference that this capability belongs to the image segmentation category (imageseg20191230) and its name is SegmentCommonImage. You need to change ocr20191230 in the code to imageseg20191230 and RecognizeBankCard to SegmentCommonImage.

  2. You must change the endpoint to the one for the correct capability category. If the endpoint does not match the category, an InvalidAction.NotFound error is returned. For more information about endpoints, see Endpoints.

  3. The request must use the package and class of the corresponding capability.

  4. The client method name must match the capability that you are calling. The method name is generated based on the capability name. For example, if the capability name is SegmentCommonImage, the corresponding method name is segment_common_image_advance.

FAQ

Handling API call errors

If an API call fails, first upgrade the SDK package to the latest version. For links to the latest SDKs, see the tables in the Prerequisites section. If your application imports packages from multiple categories, upgrade all of them to their latest versions to avoid potential package conflicts.

Latest package unavailable in PyPI

If the latest package version from OpenAPI Explorer is not available in the PyPI repository, it may be due to a synchronization delay after a new version is released. Please wait and try again later, or use the latest version currently available in the PyPI repository.

Finding request and response parameter names

Request and response parameter names in the SDK are generated from the parameter names in the API reference, following specific naming conventions. For example, a parameter named ImageURL in the API reference corresponds to the image_url parameter in the Python SDK. The corresponding stream parameter is named image_urlobject. We recommend using an IDE such as PyCharm to inspect the source code and find parameter names. Alternatively, you can call request.__dict__ or response.__dict__ to view the class attributes.

Technical support

If you still have issues after trying these suggestions, contact us by joining the Alibaba Cloud Vision Intelligence Platform support group on DingTalk (ID: 23109592). Our technical team will be available to help you.