Python SDK guide
This topic describes how to use the Alibaba Cloud software development kit (SDK) for Python to call Document Mind API operations. You can use these operations to extract hierarchical structures, text content, key-value (KV) fields, and style information from documents.
Preparations
Before you use the Python SDK to call Document Mind OpenAPI operations, you must complete the following preparations.
Prepare the environment
Download and install Python 3. If Python is already installed, check its version:
python --version.Install the core library for the Python SDK. Run the following commands in your terminal to install the dependencies:
pip install alibabacloud_tea_openapi
pip install alibabacloud_docmind_api20220711Configure identity authentication
Create an AccessKey pair. For more information, see Create an AccessKey pair.
Create a Resource Access Management (RAM) user. You can create RAM users and grant them specific permissions. This is useful if multiple users in your enterprise need to access cloud resources. Use RAM to assign the least privilege required for each user. This practice avoids sharing your Alibaba Cloud account password or AccessKey and reduces security risks. We recommend that you use a predefined access policy to quickly create and authorize a RAM user. For more information, see Quick Start: Create and authorize a RAM user.
ImportantBy default, an Alibaba Cloud account has administrator permissions for all of its cloud resources. These permissions cannot be changed. If the AccessKey of an Alibaba Cloud account is leaked, all resources that belong to the account are at risk. For improved security, we recommend that you do not create an AccessKey for your Alibaba Cloud account. Instead, create an AccessKey for a RAM user and grant the user the least privilege required.
Do not hardcode your AccessKey ID and AccessKey secret into your project code. This helps prevent credential leaks. For more information about how to use credentials securely, see Securely use credentials.
Add the Alibaba Cloud SDK Credentials dependency:
pip install alibabacloud_credentialsConfigure identity authentication. This topic uses a configuration file as an example. For more information, see Manage access credentials.
Call OpenAPI operations
Document Mind operations are asynchronous. You must first call the `SubmitDocStructureJobAdvance` or `SubmitDocStructureJob` operation to submit an asynchronous task, and then call the `GetDocStructureResult` operation to poll for the result.
We recommend that you poll for the result every 10 seconds for a maximum of 120 minutes. If the task is not complete after 120 minutes, the request times out.
After a task is complete, you can retrieve the result within 24 hours. The result is deleted after 24 hours.
View OpenAPI documentation
Before you call an API operation, review its documentation to understand the required parameters and permissions. For more information, see API overview.
Call an API operation to submit a document processing task
You can submit an asynchronous task in two ways: using a local file or a file URL.
To upload a local file, use the `SubmitDocStructureJobAdvance` operation.
To upload a file from a URL, use the `SubmitDocStructureJob` operation.
If you are processing a large file that requires a long processing time, set the following properties for the `config` object.
# Connection timeout
config.connect_timeout = 60000;
# Read timeout
config.read_timeout = 60000;Submit an asynchronous task with a local document
The following code provides an example of how to call the `SubmitDocStructureJobAdvance` operation to submit a task by uploading a local file.
The operations for converting images to Word, Excel, or PDF files do not support local file uploads. These operations only support file uploads from a URL.
# -*- coding: utf-8 -*-
import sys
from typing import List
from alibabacloud_docmind_api20220711.client import Client as docmind_api20220711Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_docmind_api20220711 import models as docmind_api20220711_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea_util import models as util_models
from alibabacloud_credentials.client import Client as CredClient
def create_client() -> docmind_api20220711Client:
"""
@return: Client
@throws Exception
"""
# When you call the API operation, the program directly accesses the credentials, reads your AccessKey, and automatically performs authentication.
# Before you run this example, complete Step 2: Configure identity authentication.
# This example uses the default configuration file to create default access credentials by configuring the Credentials file.
# Use the default credentials to initialize the Credentials client.
cred=CredClient()
config = open_api_models.Config(
# Obtain the AccessKey ID from the configuration using Credentials.
access_key_id=cred.get_credential().access_key_id,
# Obtain the AccessKey secret from the configuration using Credentials.
access_key_secret=cred.get_credential().access_key_secret
)
# The endpoint to access.
config.endpoint = f'docmind-api.cn-hangzhou.aliyuncs.com'
return docmind_api20220711Client(config)
if __name__ == '__main__':
client = create_client()
request = docmind_api20220711_models.SubmitDocStructureJobAdvanceRequest(
# file_url_object: The local file stream.
file_url_object=open("./example.pdf", "rb"),
# file_name: The name of the file. The name must include the file extension.
file_name='123.pdf',
# file_name_extension: The file extension. Use either this parameter or file_name.
file_name_extension='pdf'
)
runtime = util_models.RuntimeOptions()
try:
# If you copy the code to run, print the API return value.
response = client.submit_doc_structure_job_advance(request, runtime)
# The format of the API return value is body -> data -> specific property. You can print the corresponding results as needed. The following example shows how to print the returned business ID.
# The names of the properties to obtain start with a lowercase letter.
print(response.body)
except Exception as error:
# If necessary, print the error.
UtilClient.assert_as_string(error.message)Return value
{
"RequestId": "B2969F25-1A0B-5F08-9A16-EE694AD0****",
"Data": {
"Id": "docmind-20220922-b15f****"
}
}Submit a task by providing a document URL
The document URL must be publicly accessible for download, without any cross-domain restrictions or special escape characters. The following code shows an example of how to call the `SubmitDocStructureJob` operation by providing a document URL.
# -*- coding: utf-8 -*-
import sys
from typing import List
from alibabacloud_docmind_api20220711.client import Client as docmind_api20220711Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_docmind_api20220711 import models as docmind_api20220711_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_credentials.client import Client as CredClient
def create_client() -> docmind_api20220711Client:
"""
@return: Client
@throws Exception
"""
# When you call the API operation, the program directly accesses the credentials, reads your AccessKey, and automatically performs authentication.
# Before you run this example, complete Step 2: Configure identity authentication.
# This example uses the default configuration file to create default access credentials by configuring the Credentials file.
# Use the default credentials to initialize the Credentials client.
cred=CredClient()
config = open_api_models.Config(
# Obtain the AccessKey ID from the configuration using Credentials.
access_key_id=cred.get_credential().get_access_key_id(),
# Obtain the AccessKey secret from the configuration using Credentials.
access_key_secret=cred.get_credential().get_access_key_secret()
)
# The endpoint to access.
config.endpoint = f'docmind-api.cn-hangzhou.aliyuncs.com'
return docmind_api20220711Client(config)
if __name__ == '__main__':
client = create_client()
request = docmind_api20220711_models.SubmitDocStructureJobRequest(
# file_url: The URL of the file.
file_url='https://example.com/example.pdf',
# file_name: The name of the file. The name must include the file extension.
file_name='123.pdf',
# file_name_extension: The file extension. Use either this parameter or file_name.
file_name_extension='pdf'
)
try:
# If you copy the code to run, print the API return value.
response = client.submit_doc_structure_job(request)
# The format of the API return value is body -> data -> specific property. You can print the corresponding results as needed. The following example shows how to print the returned business ID.
# The names of the properties to obtain start with a lowercase letter.
print(response.body)
except Exception as error:
# If necessary, print the error.
UtilClient.assert_as_string(error.message)
Return value
{
"RequestId": "43A29C77-405E-4CC0-BC55-EE694AD0****",
"Data": {
"Id": "docmind-20220712-b15f****"
}
}Query APIs for call results
The status of a task can be `processing`, `successful`, or `failed`. The following code provides an example of how to call an operation to query the task status.
# -*- coding: utf-8 -*-
import sys
from typing import List
from alibabacloud_docmind_api20220711.client import Client as docmind_api20220711Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_docmind_api20220711 import models as docmind_api20220711_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_credentials.client import Client as CredClient
def create_client() -> docmind_api20220711Client:
"""
@return: Client
@throws Exception
"""
# When you call the API operation, the program directly accesses the credentials, reads your AccessKey, and automatically performs authentication.
# Before you run this example, complete Step 2: Configure identity authentication.
# This example uses the default configuration file to create default access credentials by configuring the Credentials file.
# Use the default credentials to initialize the Credentials client.
cred=CredClient()
config = open_api_models.Config(
# Obtain the AccessKey ID from the configuration using Credentials.
access_key_id=cred.get_credential().get_access_key_id(),
# Obtain the AccessKey secret from the configuration using Credentials.
access_key_secret=cred.get_credential().get_access_key_secret()
)
# The endpoint to access.
config.endpoint = f'docmind-api.cn-hangzhou.aliyuncs.com'
return docmind_api20220711Client(config)
if __name__ == '__main__':
client = create_client()
request = docmind_api20220711_models.GetDocStructureResultRequest(
# id: The ID returned by the task submission operation.
id='docmind-20220902-824b****'
)
try:
# If you copy the code to run, print the API return value.
response = client.get_doc_structure_result(request)
# The format of the API return value is body -> data -> specific property. You can print the corresponding results as needed. The names of the properties to obtain start with a lowercase letter.
# Get the status of the asynchronous task. You can determine whether to continue polling for the result based on response.body.completed.
print(response.body.completed)
# Get the return value. We recommend that you first convert response.body.data to JSON and then retrieve the required values from the JSON object.
print(response.body)
except Exception as error:
# If necessary, print the error.
UtilClient.assert_as_string(error.message)
Result
The result can be `processing`, `successful`, or `failed`.
The following response indicates that the task is still processing. The `Completed` field is `false`, which means the task is not finished. You must continue to poll until the `Completed` field is `true` or the maximum polling time is reached.
{ "RequestId": "2AABD2C2-D24F-12F7-875D-683A27C3****", "Completed": false, "Code": "DocProcessing", "Message": "Document processing", "HostId": "ocr-api.cn-hangzhou.aliyuncs.com", "Recommend": "https://next.api.aliyun.com/troubleshoot?q=DocProcessing&product=docmind-api" }The following response indicates that the task was successful. The `Completed` field is `true`, and the `Status` field is `Success`. The processing results are in the `Data` object.
{ "Status": "Success", "RequestId": "73134E1A-E281-1B2C-A105-D0EF****", "Completed": true, "Data": { "styles": [{ "styleId": 0, "underline": false, "deleteLine": false, "bold": true, "italic": false, "fontSize": 15, "fontName": "SimHei", "color": "000000", "charScale": 0.95 }, { "styleId": 1, "underline": false, "deleteLine": false, "bold": false, "italic": false, "fontSize": 12, "fontName": "Microsoft YaHei", "color": "000000", "charScale": 1 } ], "layouts": [{ "text": "Test Title", "index": 0, "uniqueId": "xxxx9816e77caea338df554b80ab95c7", "alignment": "center", "pageNum": [ 0 ], "pos": [{ "x": 405, "y": 192 }, { "x": 860, "y": 191 }, { "x": 860, "y": 236 }, { "x": 406, "y": 237 } ], "type": "title", "subType":"doc_title" }, { "text": "This paragraph is for testing.", "index": 1, "uniqueId": "xxxx8606c213c01c12d70f98dcfb2525", "alignment": "left", "pageNum": [ 0 ], "pos": [{ "x": 187, "y": 311 }, { "x": 1075, "y": 311 }, { "x": 1076, "y": 373 }, { "x": 187, "y": 373 } ], "type": "text", "subType":"para", "lineHeight": 7, "firstLinesChars": 30, "blocks": [{ "text": "This paragraph", "pos": null, "styleId": 0 }, { "text": "is for testing.", "pos": null, "styleId": 1 } ] }], "logics": { "docTree": [{ "uniqueId": "xxxx9816e77caea338df554b80ab95c7", "level": 0, "link": { "child": [ ], "contains": [ ] }, "backlink": { "parent": [ "ROOT" ] } }], "paragraphKVs": null, "tableKVs": null }, "docInfo": { "docType": "pdf", "orignalDocName": "1.pdf", "pages": [{ "imageType": "JPEG", "imageUrl": "http://test.moshi.aliyuncs.com/docMind/image/xxxx3cccbfec45b48d3a8081c9c9659e/0", "angle": null, "imageWidth": 1273, "imageHeight": 1801, "pageIdCurDoc": 1, "pageIdAllDocs": 1 }] } } }The following response indicates that the task failed. The `Completed` field is `true`, but the `Status` field is `Fail`. The response also includes an error `Code` and a detailed `Message`. For more information about error codes, see Error codes.
{ "RequestId": "A8EF3A36-1380-1116-A39E-B377BE27****", "Completed": true, "Status": "Fail", "Code": "UrlNotLegal", "Message": "Failed to process the document. The document url you provided is not legal.", "HostId": "docmind-api.cn-hangzhou.aliyuncs.com", "Recommend": "https://next.api.aliyun.com/troubleshoot?q=IDP.UrlNotLegal&product=docmind-api" }