一、获取百度AI的的AccessToken
# 获取百度的AccessTokendef GetAccessToken():apiKey = "xxx"secretKet = "xxx"# url不需要修改url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}&".format(apiKey, secretKet)response = requests.post(url=url)return eval(response.text)["access_token"]
二、通过百度AI识别发票信息
这段是从类函数里面摘抄出来改的,可能会有点小小的bug,用的时候再改吧。
# 通过百度云识别发票信息def get_response(fileName):# 发票文件转换为二进制f = open(fileName, 'rb')invoiceFile = base64.b64encode(f.read())# 设置urlrequest_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice"access_token = "xxx"# 根据前两行自动设置request_url = request_url + "?access_token=" + access_token# 设置其他参数headers = {'content-type': 'application/x-www-form-urlencoded'}# 默认是图片params = {"image": invoiceFile}# 如果是pdf转pdfif ".pdf" in fileName:params = {"pdf_file": invoiceFile}response = requests.post(request_url, data=params, headers=headers)# 保存到selfresponse = response.json()['words_result']return response
