# -*- coding:utf-8 -*-
import base64
import requests
import time

access_token = None
token_time = 0


def high_ocr_location(pic_path):
    """
    通用文字识别（高精度含位置版）
    """
    global access_token, token_time
    with open(pic_path, 'rb') as f:
        img = base64.b64encode(f.read())

    if time.time()-token_time>3600*8:
        print("获取token啦")
        url_token = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=BaL3yDflxe7Z5001vF8rAzKu&client_secret=xs40HshFLDDyWgCCfgnz86zWhQ8X1s5f'
        token = requests.post(url_token).json()
       
        access_token = token['access_token']
        token_time = time.time()

    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate"

    params = {"image": img,"recognize_granularity":"small"}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        r_json = response.json()
       
        return r_json


if __name__ == '__main__':
    print(high_ocr_location(r"C:\Users\86131\Desktop\4.jpg"))