Tengxun Cloud International Account: OCR Text Recognition API Integration Tutorial: Quickly Realize Document and Certificate Recognition
In today's software development and enterprise digital transformation,
OCR (Optical Character Recognition)
It is definitely a high-frequency and just-needed function. Whether it is the identification of identity cards during user real-name authentication, the automatic entry of invoices by the financial system, or the rapid electronic of paper documents, OCR can help us save a lot of manual entry costs.
There are many OCR services on the market, but from
Identification accuracy, coverage of domestic documents/bills, and interface stability
Tencent Cloud's text recognition (OCR) service has been in the first echelon.
Today's article, I will take you through it from the perspective of a real developer.
Integration and Development of Tencent Cloud OCR API
, take you to quickly realize the automatic identification of common documents and various certificates!
Why did 1. choose Tencent Cloud OCR?
Before formally writing the code, let's talk about why many enterprises and developers give priority to Tengxun Cloud OCR when selecting models:
Category is extremely rich: in addition to basic general printing and handwriting recognition, in-depth model optimization has been made for dozens of specific scenes such as ID card, driver's license, business license, VAT invoice, bank card, etc., with extremely high accuracy.
The response is extremely fast out of the box: you do not need to train your own deep learning model, directly call the RESTful API or official SDK, and return structured JSON results in milliseconds.
Security and compliance protection: For sensitive document information such as ID cards, Tencent Cloud provides a high-standard data security transmission and compliance protection mechanism.
💡Pre-preparation tip: Before calling Tengxun Cloud API, you need to have a Tengxun Cloud account with real name authentication and open OCR service. If you are an enterprise team, a service provider, or need to purchase computing resources in batches, it is recommended to purchase and open Tengxun cloud accounts through formal channels, which not only facilitates unified invoicing and management, but also often enjoys more cost-effective exclusive package discounts and architect access support.
Pre -2. integration preparations
Before writing Python/Java code, we need to get the "key" necessary to call the API in the Tengxun cloud console ":
1. Get the key (SecretId and SecretKey)
Log in to the Tencent Cloud console and go to Access Management (CAM) -> API Key Management.
Click "New Key", the system will automatically generate a pair of SecretId and SecretKey.
Note: These two keys are the unique credentials for calling the API. Do not hard-code them into the front-end code or submit them to the GitHub public repository!
2. Open OCR service and free quota
Enter the tengxunyun OCR console and start the identification service you need (for example, ID card identification
IDCardOCR
or General Print Identification
GeneralBasicOCR
). Tencent Cloud usually provides new users with a certain monthly free quota, which is very suitable.
development testing.
3. Practical Exercise: Python Quickly Integrates Tengxun Cloud OCR
Next we use the most popular and well-maintained
Tencent Cloud official SDK(TencentCloud SDK for Python)
to carry out actual combat.
Step 1: Install the official SDK
Open a terminal or command line and run the following command to install the Python SDK:
pip install tencentcloud-sdk-python
Step 2: Core code implementation (take ID card identification as an example)
ID card identification is the most common requirement in the scene. Tengxunyun OCR can automatically identify the name, gender, nationality, date of birth, address, ID card number, and even judge the front and back of the ID card and trim alarm.
Create one
ocr_demo.py
file, write the following code:
import base64
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models
def recognize_id_card(image_path):try:
#1. Key initialization (recommended reading from environment variables or configuration files, never hard-coding)
secret_id = "YOUR_SECRET_ID"
secret_key = "YOUR_SECRET_KEY"
cred = credential.Credential(secret_id, secret_key)
#2.
Configuring HTTP Options and Client Properties
httpProfile = HttpProfile()
httpProfile.endpoint = "ocr.tencentcloudapi.com"# OCR API Domain Name
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
#3. Instantiate the OCR client (specify the region, such as Guangzhou, ap-guangzhou)
client = ocr_client. OcrClient(cred, "ap-guangzhou", clientProfile)
#4. Convert the local picture into Base64 encoding (you can also directly transfer the public network URL of the picture) withopen(image_path, "rb") as f:
base64_data = base64.b64encode(f.read()).decode("utf-8")
#5. Build the request object
req = models.IDCardOCRRequest()
params = {
"ImageBase64": base64_data,
"CardSide": "FRONT"# FRONT means portrait face, BACK means national emblem face
}
&n
bsp; req.from_json_string(json.dumps(params))
#6. Initiate an API request
resp = client.IDCardOCR(req)
#7. Parse and output results
result = json.loads(resp.to_json_string())
print("--- Recognition Result ---")
print(f "Name: {result.get('Name')}")
print(f "Gender: {result.get('Sex')}")
print(f "ID number: {result.get('IdNum')}")
print(f "Address: {result.get('Address')}")
return result
except TencentCloudSDKException as err:
print(f "API call exception: {err}")
# Test run if __name__ = = "__main__":
recognize_id_card("my_id_card.jpg")
Step 3: Generic Document/Form Recognition Extension
If you need to identify paper documents, PDFs or forms, just switch the API method. For example using
General Print Recognition (GeneralBasicOCR)
:
# Just replace the request object with the called method
req = models.GeneralBasic
OCRRequest()
params = {"ImageBase64": base64_data}
req.from_json_string(json.dumps(params))
resp = client.GeneralBasicOCR(req)
# resp will contain the position coordinates (Polygon) of the text block and the recognized text content
4. production environment landing pit guide
When actually bringing the OCR function online to the production environment, there are several key optimization points that can help you greatly improve the stability and experience of the system:
Image Preprocessing and Compression The Tengxun Cloud API has a limit on the size of incoming images (usually no more than 7MB/10MB after Base64 encoding). Suggestion: Proper scaling and JPEG compression should be carried out on the front end or server before uploading, which can not only avoid overrun, but also greatly reduce the time consumption of network transmission and improve the response speed.
URL transmission is preferred. If your picture is already stored in object storage (such as Tengxun Cloud COS), try to transmit the picture URL instead of Base64 string, which can greatly reduce the server memory usage and network bandwidth pressure.
Timeout and Retry Mechanism Network occasional jitter is inevitable. When calling the client, we recommend that you set a reasonable timeout period (for example, 3 to 5 seconds) and capture the TencentCloudSDKException in the code to implement exponential backoff retry.
Security Compliance of Sensitive Data After identifying personal privacy data such as ID cards and bank cards, remember not to print the complete card number and sensitive fields in clear text in the log. It is recommended to desensitize the data before dropping the data.
Summary
Through the practical operation of this article, you can see that the integration of Tengxun Cloud OCR text recognition API is actually very simple, with only a few dozen lines of Python code to quickly build a powerful document and document recognition capability.
Whether it is building an enterprise's automated office system or developing consumer-oriented App/applets, Tengxun Cloud OCR can provide extremely high accuracy and stability. If you are preparing to access relevant functions in the project, it is recommended to do a good job of architecture and computing power evaluation in advance, choose a regular
Purchase a Tencent Cloud account
And service channels, not only can reduce the initial operation and maintenance costs, but also to ensure the high availability of subsequent business expansion!
