import requests
import base64
import hashlib
import time
import random
import os, string, glob
from urllib.parse import urlencode
class UseTencent(object):
def __init__(self, AppID=None, AppKey=None):
self.app_id = AppID
self.app_key = AppKey
self.img_base64str = ''
def get_random_str(self):
# 随机生成16位字符串
rule = string.ascii_lowercase + string.digits
str = random.sample(rule, 16)
return "".join(str)
def get_time_stamp(self):
return str(int(time.time()))
def get_img_base64str(self, image):
with open(image, 'rb') as fp:
imgbase64 = base64.b64encode(fp.read())
self.img_base64str = imgbase64
return self.img_base64str.decode()
def get_dict_md5(self, req_dict, app_key):
try:
# 方法,先对字典排序,排序之后,写app_key,再urlencode
sort_dict = sorted(req_dict.items(), key=lambda item: item[0], reverse=False)
sort_dict.append(('app_key', app_key))
sha = hashlib.md5()
rawtext = urlencode(sort_dict).encode()
sha.update(rawtext)
md5text = sha.hexdigest().upper()
if md5text:
req_dict['sign'] = md5text
return md5text
except Exception as e:
return None
# 生成字典
def get_req_dict(self, req_dict):
"""用MD5算法生成安全签名"""
req_dict['app_id'] = self.app_id
req_dict['time_stamp'] = self.get_time_stamp()
req_dict['nonce_str'] = self.get_random_str()
app_key = self.app_key
self.get_dict_md5(req_dict, app_key)
# 改成你自己的API账号、密码
APPID = '*******'
APPKEY = '********'
TencentAPI = {
"ocr_generalocr": {
'APINAME': '通用OCR识别',
'APIDESC': '识别上传图像上面的字段信息',
'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr',
'APIPARA': 'image'
}
}
# Apiname='ocr_generalocr', image=file
def ExecTecentAPI(Apiname, image):
url = TencentAPI[Apiname]['APIURL']
name = TencentAPI[Apiname]['APINAME']
desc = TencentAPI[Apiname]['APIDESC']
key = TencentAPI[Apiname]['APIPARA']
tx = UseTencent(APPID, APPKEY)
Req_Dict = {
}
value = tx.get_img_base64str(image)
Req_Dict[key] = value
# 生成请求包
tx.get_req_dict(req_dict=Req_Dict)
resp = requests.post(url, data=Req_Dict, verify=False)
# print(name + '执行结果' + resp.text)
return resp.text
def user(file):
rest = ExecTecentAPI(Apiname='ocr_generalocr', image=file)
rest = eval(rest)
list_txt = ''
for item in rest[u'data'][u'item_list']:
# print(item[u'itemstring'])
list_txt = list_txt + item[u'itemstring']
print(list_txt)
return list_txt
if __name__ == "__main__":
file = r'E:\python\\1.png'
user(file)
腾讯api调用
猜你喜欢
转载自blog.csdn.net/qq_37386287/article/details/82532955
今日推荐
周排行