当前位置:   article > 正文

Python3 下实现 腾讯人工智能API 调用_腾讯ai 调用

腾讯ai 调用

朋友们,如需转载请标明出处:http://blog.csdn.net/jiangjunshow

 

1、背景

a、鹅厂近期发布了自己的人工智能 api,包括身份证ocr、名片ocr、文本分析等一堆API,因为前期项目用到图形OCR,遂实现试用了一下,发现准确率还不错,放出来给大家共享一下。

b、基于python3,跟python2还是有些区别。

c、特别需要提到的就是签名生成这块,鹅厂的api说明里写的比较简单,一开始在sign的生成(https://ai.qq.com/doc/auth.shtml)上卡了好几天,后来加的官方群,咨询之后才解决。

 

2、签名算法

不够150字,那就正好把签名算法这块写一写。

a、官网说明如下:

按URL键值拼接字符串T

依照算法第二步要求,将参数对列表N的参数对进行URL键值拼接,值使用URL编码,URL编码算法用大写字母,例如%E8,而不是小写%e8,得到字符串T如下:

 

b、实际上:

参数列表是指api中所有除sign之外用到的参数都要参与计算sign。

譬如:

1)文本分析接口有4个字段,拼接串为:

app_id=10000&nonce_str=20e3408a79&text=%E8%85%BE%E8%AE%AF%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0&time_stamp=1493449657

参数名参数值
app_id10000
nonce_str20e3408a79
text腾讯开放平台
time_stamp1493449657

 

2)身份证ocr接口有6个字段,拼接串为:

app_id=10000&time_stamp=1511839575&nonce_str=3oxitu0qf198bh24&image=%2F9j%2F4AA************QSkZJRgA9j%2F%2F2Q%3D%3D&card_type=0&sign=2ED0122CD44DCB1FD7BC9AE1D03D64D9

参数名称是否必选数据类型数据约束示例数据描述
app_idint正整数1000001应用标识(AppId)
time_stampint正整数1493468759请求时间戳(秒级)
nonce_strstring非空且长度上限32字节fa577ce340859f9fe随机字符串
signstring非空且长度固定32字节B250148B284956EC5218D4B0503E7F8A签名信息,详见接口鉴权
imagestring原始图片的base64编码数据(解码后大小上限1MB,支持JPG、PNG、BMP格式)...待识别图片
card_typeint整数0/1身份证图片类型,0-正面,1-反面

 

注意区别:不光光是参与计算的字段变化,各字段的排序也不一样。

 

 

 

3、实现代码

在github上上传了一下,https://github.com/jdstkxx/pyTencentAI

 

 

复制代码

  1. # -*- coding: utf-8 -*-
  2. '''
  3. create by : joshua zou
  4. create date : 2017.11.28
  5. Purpose: tecent ai api
  6. '''
  7. import requests
  8. import base64
  9. import hashlib
  10. import time
  11. import random
  12. import os,string,glob
  13. from PIL import Image
  14. from io import BytesIO
  15. from urllib.parse import urlencode
  16. from urllib import parse
  17. import json
  18. class MsgTencent(object):
  19. def __init__(self,AppID=None,AppKey=None):
  20. '''
  21. 改成你自己的API账号、密码
  22. '''
  23. if not AppID: AppID = '1111111111'
  24. if not AppKey: AppKey = 'uuuuuuuuuu'
  25. self.app_id= AppID
  26. self.app_key= AppKey
  27. self.img_base64str=None
  28. def get_random_str(self):
  29. #随机生成16位字符串
  30. rule = string.ascii_lowercase + string.digits
  31. str = random.sample(rule, 16)
  32. return "".join(str)
  33. def get_time_stamp(self):
  34. return str(int(time.time()))
  35. def __get_image_base64str__(self,image):
  36. if not isinstance(image,Image):return None
  37. outputBuffer = BytesIO()
  38. bg.save(outputBuffer, format='JPEG')
  39. imgbase64 = base64.b64encode(outputBuffer.getvalue())
  40. return imgbase64
  41. def __get_imgfile_base64str__(self,image):
  42. if not isinstance(image, str): return None
  43. if not os.path.isfile(image): return None
  44. with open(image,'rb') as fp:
  45. imgbase64 = base64.b64encode(fp.read())
  46. return imgbase64
  47. def get_img_base64str(self,image):
  48. if isinstance(image, str):
  49. self.img_base64str= self.__get_imgfile_base64str__(image)
  50. elif isinstance(image,Image):
  51. self.img_base64str= self.__get_imgfile_base64str__(image)
  52. return self.img_base64str.decode()
  53. # 组装字典,MD5加密方法
  54. '''
  55. ======================================
  56. tencent获得参数对列表N(字典升级排序)
  57. ======================================
  58. 1\依照算法第一步要求,对参数对进行排序,得到参数对列表N如下。
  59. 参数名 参数值
  60. app_id 10000
  61. nonce_str 20e3408a79
  62. text 腾讯开放平台
  63. time_stamp 1493449657
  64. 2\按URL键值拼接字符串T
  65. 依照算法第二步要求,将参数对列表N的参数对进行URL键值拼接,值使用URL编码,URL编码算法用大写字母,例如%E8,而不是小写%e8,得到字符串T如下:
  66. app_id=10000&nonce_str=20e3408a79&text=%E8%85%BE%E8%AE%AF%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0&time_stamp=1493449657
  67. 3\拼接应用密钥,得到字符串S
  68. 依照算法第三步要求,将应用密钥拼接到字符串T的尾末,得到字符串S如下。
  69. app_id=10000&nonce_str=20e3408a79&text=%E8%85%BE%E8%AE%AF%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0&time_stamp=1493449657&app_key=a95eceb1ac8c24ee28b70f7dbba912bf
  70. 4\计算MD5摘要,得到签名字符串
  71. 依照算法第四步要求,对字符串S进行MD5摘要计算得到签名字符串如。
  72. e8f6f347d549fe514f0c9c452c95da9d
  73. 5\转化md5签名值大写
  74. 对签名字符串所有字母进行大写转换,得到接口请求签名,结束算法。
  75. E8F6F347D549FE514F0C9C452C95DA9D
  76. 6\最终请求数据
  77. 在完成签名计算后,即可得到所有接口请求数据,进一步完成API的调用。
  78. text 腾讯开放平台 接口请求数据,UTF-8编码
  79. app_id 10000 应用标识
  80. time_stamp 1493449657 请求时间戳(秒级),用于防止请求重放
  81. nonce_str 20e3408a79 请求随机字符串,用于保证签名不可预测
  82. sign E8F6F347D549FE514F0C9C452C95DA9D 请求签名
  83. '''
  84. def gen_dict_md5(self,req_dict,app_key):
  85. if not isinstance(req_dict,dict) :return None
  86. if not isinstance(app_key,str) or not app_key:return None
  87. try:
  88. #方法,先对字典排序,排序之后,写app_key,再urlencode
  89. sort_dict= sorted(req_dict.items(), key=lambda item:item[0], reverse = False)
  90. sort_dict.append(('app_key',app_key))
  91. sha = hashlib.md5()
  92. rawtext= urlencode(sort_dict).encode()
  93. sha.update(rawtext)
  94. md5text= sha.hexdigest().upper()
  95. #print(1)
  96. #字典可以在函数中改写
  97. if md5text: req_dict['sign']=md5text
  98. return md5text
  99. except Exception as e:
  100. return None
  101. #生成字典
  102. def gen_req_dict(self, req_dict,app_id=None, app_key=None,time_stamp=None, nonce_str=None):
  103. """用MD5算法生成安全签名"""
  104. if not req_dict.get('app_id'):
  105. if not app_id: app_id= self.app_id
  106. req_dict['app_id']= app_id
  107. #nonce_str 字典无值
  108. if not req_dict.get('time_stamp'):
  109. if not time_stamp: time_stamp= self.get_time_stamp()
  110. req_dict['time_stamp']= time_stamp
  111. if not req_dict.get('nonce_str'):
  112. if not nonce_str: nonce_str= self.get_random_str()
  113. req_dict['nonce_str']= nonce_str
  114. #app_key 取系统参数。
  115. if not app_key: app_key= self.app_key
  116. md5key= self.gen_dict_md5(req_dict, app_key)
  117. return md5key
  118. '''
  119. 基本文本分析
  120. ===========
  121. 分词 对文本进行智能分词识别,支持基础词与混排词粒度 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordseg text
  122. 词性标注 对文本进行分词,同时为每个分词标注正确的词性 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordpos text
  123. 专有名词识别 对文本进行专有名词的分词识别,找出文本中的专有名词 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordner text
  124. 同义词识别 识别文本中存在同义词的分词,并返回相应的同义词 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordsyn text
  125. 计算机视觉--OCR识别
  126. ====================
  127. 通用OCR识别 识别上传图像上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr image
  128. 身份证OCR识别 识别身份证图像上面的详细身份信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr image,card_type(身份证,0-正面,1-反面)
  129. 名片OCR识别 识别名片图像上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_bcocr image
  130. 行驶证驾驶证OCR识别 识别行驶证或驾驶证图像上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_driverlicenseocr image,type(识别类型,0-行驶证识别,1-驾驶证识别)
  131. 营业执照OCR识别 识别营业执照上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_bizlicenseocr image
  132. 银行卡OCR识别 识别银行卡上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr image
  133. '''
  134. #改成你自己的API账号、密码
  135. APPID='1111111111'
  136. APPKEY='UUUUUUUUU'
  137. TencentAPI={
  138. #基本文本分析API
  139. "nlp_wordseg": {
  140. 'APINAME':'分词',
  141. 'APIDESC': '对文本进行智能分词识别,支持基础词与混排词粒度',
  142. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordseg',
  143. 'APIPARA': 'text'
  144. },
  145. "nlp_wordpos": {
  146. 'APINAME':'词性标注',
  147. 'APIDESC': '对文本进行分词,同时为每个分词标注正确的词性',
  148. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordpos',
  149. 'APIPARA': 'text'
  150. },
  151. 'nlp_wordner': {
  152. 'APINAME':'专有名词识别',
  153. 'APIDESC': '对文本进行专有名词的分词识别,找出文本中的专有名词',
  154. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordner',
  155. 'APIPARA': 'text'
  156. },
  157. 'nlp_wordsyn': {
  158. 'APINAME':'同义词识别',
  159. 'APIDESC': '识别文本中存在同义词的分词,并返回相应的同义词',
  160. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordsyn',
  161. 'APIPARA': 'text'
  162. },
  163. #计算机视觉--OCR识别API
  164. "ocr_generalocr": {
  165. 'APINAME':'通用OCR识别',
  166. 'APIDESC': '识别上传图像上面的字段信息',
  167. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr',
  168. 'APIPARA': 'image'
  169. },
  170. "ocr_idcardocr": {
  171. 'APINAME':'身份证OCR识别',
  172. 'APIDESC': '识别身份证图像上面的详细身份信息',
  173. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr',
  174. 'APIPARA': 'image,card_type'
  175. },
  176. "ocr_bcocr": {
  177. 'APINAME':'名片OCR识别',
  178. 'APIDESC': '识别名片图像上面的字段信息',
  179. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_bcocr',
  180. 'APIPARA': 'image'
  181. },
  182. "ocr_driverlicenseocr":{
  183. 'APINAME':'行驶证驾驶证OCR识别',
  184. 'APIDESC': '识别行驶证或驾驶证图像上面的字段信息',
  185. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_driverlicenseocr',
  186. 'APIPARA': 'image,type'
  187. },
  188. "ocr_bizlicenseocr":{
  189. 'APINAME':'营业执照OCR识别',
  190. 'APIDESC': '识别营业执照上面的字段信息',
  191. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_bizlicenseocr',
  192. 'APIPARA': 'image'
  193. },
  194. "ocr_creditcardocr":{
  195. 'APINAME':'银行卡OCR识别',
  196. 'APIDESC': '识别银行卡上面的字段信息',
  197. 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr',
  198. 'APIPARA': 'image'
  199. },
  200. }
  201. def ExecTecentAPI(*arg,**kwds):
  202. if kwds.get('Apiname'): apiname= kwds.pop('Apiname')
  203. url = TencentAPI[apiname]['APIURL']
  204. name = TencentAPI[apiname]['APINAME']
  205. desc= TencentAPI[apiname]['APIDESC']
  206. para= TencentAPI[apiname]['APIPARA']
  207. tx= MsgTencent(APPID,APPKEY)
  208. Req_Dict={}
  209. for key in para.split(','):
  210. value=None
  211. print (kwds)
  212. if kwds.get(key): value = kwds.pop(key)
  213. if key=='image':
  214. #图像获取base64
  215. value= tx.get_img_base64str(value)
  216. if key=='text':
  217. #文本进行GBK编码
  218. value= value.encode('gbk')
  219. Req_Dict[key]=value
  220. print (key,value,Req_Dict[key])
  221. #生成请求包
  222. sign= tx.gen_req_dict(req_dict=Req_Dict)
  223. resp = requests.post(url,data=Req_Dict,verify=False)
  224. print (name+'执行结果'+resp.text)
  225. return resp.text
  226. if __name__ == "__main__":
  227. #名片ocr
  228. file= r'名片.jpg'
  229. rest = ExecTecentAPI(Apiname='ocr_bcocr',image=file)
  230. #文本分析
  231. rest = ExecTecentAPI(Apiname='nlp_wordseg',text='上帝保佑你')

复制代码

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/998450
推荐阅读
相关标签
  

闽ICP备14008679号