import requests
import base64
import urllib
API_KEY = "6FddDb96GQ8XoGy0hwwzSpGc"
SECRET_KEY = "xPfQXsztgQxXNrP2GbIRGO3gLLGmQUHd"


def get_access_token():
    # 实现获取访问令牌的逻辑
    access_token = "your_access_token"
    return access_token

def get_file_content_as_base64(file_path, is_binary=False):
    # 实现将文件转换为base64编码的逻辑
    return file_content_as_base64

def get_license_plate_number(image_path):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + get_access_token()
    payload = 'image=' + get_file_content_as_base64(image_path, True)
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    license_plate_number = response.json()['words_result']['number']
    return license_plate_number

def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))
