Files

58 lines
2.2 KiB
Python

import os
import base64
import requests
import json
from pathlib import Path
def get_access_token(api_key, secret_key):
url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}"
payload = ""
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
return response.json().get("access_token")
def test_general_ocr(image_path, api_key, secret_key):
# 用户要求的接口: 通用卡证票据识别
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_ocr"
with open(image_path, "rb") as f:
img = base64.b64encode(f.read())
params = {"image": img}
access_token = get_access_token(api_key, secret_key)
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
print(f"正在请求接口: {request_url}")
response = requests.post(request_url, data=params, headers=headers)
return response.json()
if __name__ == "__main__":
# 使用 config.ini 中的密钥
api_key = "yBU35EDIZ2ITLRk1MnFBN1tv"
secret_key = "7L0VEOIcqHhaqzZec5LXsHGzJhgFivMr"
# 测试图片路径
test_image = r"F:\Administrator\桌面\OCR系统_Release\data\input\采购单_20260717_优链快批销售单.jpg"
if not os.path.exists(test_image):
print(f"错误: 找不到测试图片 {test_image}")
else:
print(f"正在测试接口【/v1/general_ocr】图片: {os.path.basename(test_image)}")
result = test_general_ocr(test_image, api_key, secret_key)
print("\n--- API 返回结果 ---")
print(json.dumps(result, indent=2, ensure_ascii=False))
if "error_code" in result:
if result["error_code"] == 6:
print("\n【重要提示】: 权限错误 (6)。请前往百度云控制台开启【通用票据识别】(General OCR) 服务。")
else:
print(f"\nAPI 返回错误: {result.get('error_msg')}")
else:
print("\n识别成功!请检查返回结果中的 words_result 是否包含供应商和日期。")