Python3 下实现 腾讯人工智能API 调用
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_id | 10000 |
nonce_str | 20e3408a79 |
text | 腾讯开放平台 |
time_stamp | 1493449657 |
2)身份证ocr接口有6个字段,拼接串为:
app_id=&time_stamp=1511839575&nonce_str=3oxitu0qf198bh24&image=%2F9j%2F4AA************QSkZJRgA9j%2F%2F2Q%3D%3D&card_type=0&sign=2ED0122CD44DCB1FD7BC9AE1D03D64D9
参数名称 | 是否必选 | 数据类型 | 数据约束 | 示例数据 | 描述 |
---|---|---|---|---|---|
app_id | 是 | int | 正整数 | 1000001 | 应用标识(AppId) |
time_stamp | 是 | int | 正整数 | 1493468759 | 请求时间戳(秒级) |
nonce_str | 是 | string | 非空且长度上限32字节 | fa577ce340859f9fe | 随机字符串 |
sign | 是 | string | 非空且长度固定32字节 | B250148B284956EC5218D4B0503E7F8A | 签名信息,详见接口鉴权 |
image | 是 | string | 原始图片的base64编码数据(解码后大小上限1MB,支持JPG、PNG、BMP格式) | ... | 待识别图片 |
card_type | 是 | int | 整数 | 0/1 | 身份证图片类型,0-正面,1-反面 |
注意区别:不光光是参与计算的字段变化,各字段的排序也不一样。
3、实现代码
在github上上传了一下,https://github.com/jdstkxx/pyTencentAI
- # -*- coding: utf-8 -*-
- '''
- create by : joshua zou
- create date : 2017.11.28
- Purpose: tecent ai api
- '''
- import requests
- import base64
- import hashlib
- import time
- import random
- import os,string,glob
- from PIL import Image
- from io import BytesIO
- from urllib.parse import urlencode
- from urllib import parse
- import json
- class MsgTencent(object):
- def __init__(self,AppID=None,AppKey=None):
- '''
- 改成你自己的API账号、密码
- '''
- if not AppID: AppID = ''
- if not AppKey: AppKey = 'uuuuuuuuuu'
- self.app_id= AppID
- self.app_key= AppKey
- self.img_base64str=None
- 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_image_base64str__(self,image):
- if not isinstance(image,Image):return None
- outputBuffer = BytesIO()
- bg.save(outputBuffer, format='JPEG')
- imgbase64 = base64.b64encode(outputBuffer.getvalue())
- return imgbase64
- def __get_imgfile_base64str__(self,image):
- if not isinstance(image, str): return None
- if not os.path.isfile(image): return None
- with open(image,'rb') as fp:
- imgbase64 = base64.b64encode(fp.read())
- return imgbase64
- def get_img_base64str(self,image):
- if isinstance(image, str):
- self.img_base64str= self.__get_imgfile_base64str__(image)
- elif isinstance(image,Image):
- self.img_base64str= self.__get_imgfile_base64str__(image)
- return self.img_base64str.decode()
- # 组装字典,MD5加密方法
- '''
- ======================================
- tencent获得参数对列表N(字典升级排序)
- ======================================
- 1\依照算法第一步要求,对参数对进行排序,得到参数对列表N如下。
- 参数名 参数值
- app_id 10000
- nonce_str 20e3408a79
- text 腾讯开放平台
- time_stamp 1493449657
- 2\按URL键值拼接字符串T
- 依照算法第二步要求,将参数对列表N的参数对进行URL键值拼接,值使用URL编码,URL编码算法用大写字母,例如%E8,而不是小写%e8,得到字符串T如下:
- 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
- 3\拼接应用密钥,得到字符串S
- 依照算法第三步要求,将应用密钥拼接到字符串T的尾末,得到字符串S如下。
- 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
- 4\计算MD5摘要,得到签名字符串
- 依照算法第四步要求,对字符串S进行MD5摘要计算得到签名字符串如。
- e8f6f347d549fe514f0c9c452c95da9d
- 5\转化md5签名值大写
- 对签名字符串所有字母进行大写转换,得到接口请求签名,结束算法。
- E8F6F347D549FE514F0C9C452C95DA9D
- 6\最终请求数据
- 在完成签名计算后,即可得到所有接口请求数据,进一步完成API的调用。
- text 腾讯开放平台 接口请求数据,UTF-8编码
- app_id 10000 应用标识
- time_stamp 1493449657 请求时间戳(秒级),用于防止请求重放
- nonce_str 20e3408a79 请求随机字符串,用于保证签名不可预测
- sign E8F6F347D549FE514F0C9C452C95DA9D 请求签名
- '''
- def gen_dict_md5(self,req_dict,app_key):
- if not isinstance(req_dict,dict) :return None
- if not isinstance(app_key,str) or not app_key:return None
- 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()
- #print(1)
- #字典可以在函数中改写
- if md5text: req_dict['sign']=md5text
- return md5text
- except Exception as e:
- return None
- #生成字典
- def gen_req_dict(self, req_dict,app_id=None, app_key=None,time_stamp=None, nonce_str=None):
- """用MD5算法生成安全签名"""
- if not req_dict.get('app_id'):
- if not app_id: app_id= self.app_id
- req_dict['app_id']= app_id
- #nonce_str 字典无值
- if not req_dict.get('time_stamp'):
- if not time_stamp: time_stamp= self.get_time_stamp()
- req_dict['time_stamp']= time_stamp
- if not req_dict.get('nonce_str'):
- if not nonce_str: nonce_str= self.get_random_str()
- req_dict['nonce_str']= nonce_str
- #app_key 取系统参数。
- if not app_key: app_key= self.app_key
- md5key= self.gen_dict_md5(req_dict, app_key)
- return md5key
- '''
- 基本文本分析
- ===========
- 分词 对文本进行智能分词识别,支持基础词与混排词粒度 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordseg text
- 词性标注 对文本进行分词,同时为每个分词标注正确的词性 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordpos text
- 专有名词识别 对文本进行专有名词的分词识别,找出文本中的专有名词 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordner text
- 同义词识别 识别文本中存在同义词的分词,并返回相应的同义词 https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordsyn text
- 计算机视觉--OCR识别
- ====================
- 通用OCR识别 识别上传图像上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr image
- 身份证OCR识别 识别身份证图像上面的详细身份信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr image,card_type(身份证,0-正面,1-反面)
- 名片OCR识别 识别名片图像上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_bcocr image
- 行驶证驾驶证OCR识别 识别行驶证或驾驶证图像上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_driverlicenseocr image,type(识别类型,0-行驶证识别,1-驾驶证识别)
- 营业执照OCR识别 识别营业执照上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_bizlicenseocr image
- 银行卡OCR识别 识别银行卡上面的字段信息 https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr image
- '''
- #改成你自己的API账号、密码
- APPID=''
- APPKEY='UUUUUUUUU'
- TencentAPI={
- #基本文本分析API
- "nlp_wordseg": {
- 'APINAME':'分词',
- 'APIDESC': '对文本进行智能分词识别,支持基础词与混排词粒度',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordseg',
- 'APIPARA': 'text'
- },
- "nlp_wordpos": {
- 'APINAME':'词性标注',
- 'APIDESC': '对文本进行分词,同时为每个分词标注正确的词性',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordpos',
- 'APIPARA': 'text'
- },
- 'nlp_wordner': {
- 'APINAME':'专有名词识别',
- 'APIDESC': '对文本进行专有名词的分词识别,找出文本中的专有名词',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordner',
- 'APIPARA': 'text'
- },
- 'nlp_wordsyn': {
- 'APINAME':'同义词识别',
- 'APIDESC': '识别文本中存在同义词的分词,并返回相应的同义词',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordsyn',
- 'APIPARA': 'text'
- },
- #计算机视觉--OCR识别API
- "ocr_generalocr": {
- 'APINAME':'通用OCR识别',
- 'APIDESC': '识别上传图像上面的字段信息',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr',
- 'APIPARA': 'image'
- },
- "ocr_idcardocr": {
- 'APINAME':'身份证OCR识别',
- 'APIDESC': '识别身份证图像上面的详细身份信息',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr',
- 'APIPARA': 'image,card_type'
- },
- "ocr_bcocr": {
- 'APINAME':'名片OCR识别',
- 'APIDESC': '识别名片图像上面的字段信息',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_bcocr',
- 'APIPARA': 'image'
- },
- "ocr_driverlicenseocr":{
- 'APINAME':'行驶证驾驶证OCR识别',
- 'APIDESC': '识别行驶证或驾驶证图像上面的字段信息',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_driverlicenseocr',
- 'APIPARA': 'image,type'
- },
- "ocr_bizlicenseocr":{
- 'APINAME':'营业执照OCR识别',
- 'APIDESC': '识别营业执照上面的字段信息',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_bizlicenseocr',
- 'APIPARA': 'image'
- },
- "ocr_creditcardocr":{
- 'APINAME':'银行卡OCR识别',
- 'APIDESC': '识别银行卡上面的字段信息',
- 'APIURL': 'https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr',
- 'APIPARA': 'image'
- },
- }
- def ExecTecentAPI(*arg,**kwds):
- if kwds.get('Apiname'): apiname= kwds.pop('Apiname')
- url = TencentAPI[apiname]['APIURL']
- name = TencentAPI[apiname]['APINAME']
- desc= TencentAPI[apiname]['APIDESC']
- para= TencentAPI[apiname]['APIPARA']
- tx= MsgTencent(APPID,APPKEY)
- Req_Dict={}
- for key in para.split(','):
- value=None
- print (kwds)
- if kwds.get(key): value = kwds.pop(key)
- if key=='image':
- #图像获取base64
- value= tx.get_img_base64str(value)
- if key=='text':
- #文本进行GBK编码
- value= value.encode('gbk')
- Req_Dict[key]=value
- print (key,value,Req_Dict[key])
- #生成请求包
- sign= tx.gen_req_dict(req_dict=Req_Dict)
- resp = requests.post(url,data=Req_Dict,verify=False)
- print (name+'执行结果'+resp.text)
- return resp.text
- if __name__ == "__main__":
- #名片ocr
- file= r'名片.jpg'
- rest = ExecTecentAPI(Apiname='ocr_bcocr',image=file)
- #文本分析
- rest = ExecTecentAPI(Apiname='nlp_wordseg',text='上帝保佑你')
Python3 下实现 腾讯人工智能API 调用的更多相关文章
- 腾讯QQAndroid API调用实例(QQ分享无需登录)
腾讯QQAndroid API调用实例(QQ分享无需登录) 主要分为两个步骤: 配置Androidmanifest.xml 修改activity里边代码 具体修改如下: 1.Activity代 ...
- 腾讯地图 API 调用入门
本文仅为腾讯地图 API 调用入门,如需进阶学习,请在腾讯位置服务网站上进行学习. 登陆网址 https://lbs.qq.com/ 点击右上角的登陆按钮,需要进行注册按照流程进行就好. 完成之后,选 ...
- 讯飞云 API 语音听写 python3 调用例程
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import requests import time import gzip import urllib imp ...
- 反射实现Model修改前后的内容对比 【API调用】腾讯云短信 Windows操作系统下Redis服务安装图文详解 Redis入门学习
反射实现Model修改前后的内容对比 在开发过程中,我们会遇到这样一个问题,编辑了一个对象之后,我们想要把这个对象修改了哪些内容保存下来,以便将来查看和追责. 首先我们要创建一个User类 1 p ...
- Python3 下实现 Tencent AI 调用
1.背景 a.鹅厂近期发布了自己的AI api,包括身份证ocr.名片ocr.文本分析等一堆API,因为前期项目用到图形OCR,遂实现试用了一下,发现准确率还不错,放出来给大家共享一下. b.基于py ...
- python3下搜狗AI API实现
1.背景 a.搜狗也发布了自己的人工智能 api,包括身份证ocr.名片ocr.文本翻译等API,初试感觉准确率一般般. b.基于python3. c.也有自己的签名生成这块,有了鹅厂的底子,相对写起 ...
- 微信小程序wx.getLocation()获取经纬度及JavaScript SDK调用腾讯地图API获取某一类地址
简介 腾讯位置服务为微信小程序提供了基础的标点能力.线和圆的绘制接口等地图组件和位置展示.地图选点等地图API位置服务能力支持,使得开发者可以自由地实现自己的微信小程序产品. 在此基础上,腾讯位置服务 ...
- 30行代码消费腾讯人工智能开放平台提供的自然语言处理API
腾讯人工智能AI开放平台上提供了很多免费的人工智能API,开发人员只需要一个QQ号就可以登录进去使用. 腾讯人工智能AI开放平台的地址:https://ai.qq.com/ 里面的好东西很多,以自然语 ...
- MVC项目实践,在三层架构下实现SportsStore-09,ASP.NET MVC调用ASP.NET Web API的查询服务
ASP.NET Web API和WCF都体现了REST软件架构风格.在REST中,把一切数据视为资源,所以也是一种面向资源的架构风格.所有的资源都可以通过URI来唯一标识,通过对资源的HTTP操作(G ...
随机推荐
- python常用库 - NumPy 和 sklearn入门
Numpy 和 scikit-learn 都是python常用的第三方库.numpy库可以用来存储和处理大型矩阵,并且在一定程度上弥补了python在运算效率上的不足,正是因为numpy的存在使得py ...
- C#效率优化(2)-- 方法内联
一.JIT编译器可以通过将方法内联展开(Method Inline Expansion)来提升效率,类似C++中的内联函数(Inline Function),与C++的内联函数不同的是,C#并不支持内 ...
- js a标签 + ajax 多参数穿参
<span onclick="return haoping('{$row['jv_id']}','1')"> function haoping(id,type){ $. ...
- Python使用@property装饰类方法
Python版本:3.5.2 假如我们有一个Student类,并在其中定义了一个score属性,但是score属性会被显露出去,没办法检查参数,导致成绩可以随意更改: stu = Student() ...
- Sherman-Morrison公式及其应用
Sherman-Morrison公式 Sherman-Morrison公式以 Jack Sherman 和 Winifred J. Morrison命名,在线性代数中,是求解逆矩阵的一种方法.本篇 ...
- C# Code First 配置(二)
上一篇文章地址 C# Code First 配置 此文章主要介绍配置映射到表中的详细字段.信息等,如下: System.ComponentModel.DataAnnotations 包含的特性: At ...
- js 去掉缓存的几种方式
1.在Ajax发送请求前加上 anyAjaxObj.setRequestHeader ("If-Modified-Since","0") 2.在Ajax发送请求 ...
- VS2017进程为idXXXX 无法启动解决方案
1.对无法启动项目的 .csproj 后缀文件用记事本打开 找到<WebProjectProperties>xx</WebProjectProperties> 删掉 让后 重新 ...
- ModBus通信协议的【传输方式】
1.Modbus 传输方式 标准的Modbus口是使用一RS-232C兼容串行接口,它定义了连接口的针脚.电缆.信号位.传输波特率.奇偶校验.控制器能直接或经由Modem组网. 控制器通信使用 ...
- github-SSH模式如何配置秘钥clone远程仓库以及分支切换
一.ssh模式clone 恕我无知,之前使用git命令都是https模式,该模式每次push都需要输入账号和密码,而且速度会根据的网速的快慢而定. 近日电脑重装了系统,在用SSH模式clone远程仓库 ...