当前位置:Gxlcms > Python > python3下调用搜狗AIAPI的方法

python3下调用搜狗AIAPI的方法

时间:2021-07-01 10:21:17 帮助过:68人阅读

这次给大家带来python3下调用搜狗AI API的方法,python3下调用搜狗AI API的注意事项有哪些,下面就是实战案例,一起来看一下。

1、背景

a、搜狗也发布了自己的人工智能 api,包括身份证ocr、名片ocr、文本翻译等API,初试感觉准确率一般般。

b、基于python3。

c、也有自己的签名生成这块,有了鹅厂的底子,相对写起来比较简单。

d、不过Sougou明显在接口标准化这块明显不如鹅厂,不同api应答包的主体结构竟然不一致,所以实施也只做了简单的结构化……

2、实现代码

直接放代码吧,github上也有: https://github.com/jdstkxx/PySougouAI

1、sogouai-example.py

  1. # -*- coding: utf-8 -*-
  2. '''
  3. create by : joshua zou
  4. create date : 2018.4.9
  5. Purpose: check sougou ai api
  6. '''
  7. import glob,os
  8. from SougouAPIMsg import *
  9. #改成你自己搜狗AI的APPID、APPKEY、SecretKey
  10. AppID = '0000'
  11. ApiKey = '*********'
  12. SecretKey= '0PLvS-AHShmq**************'
  13. if name == "main":
  14. sg = SougouAPIMsg(AppID,ApiKey,SecretKey)
  15. for file in glob.glob('D:\python\*.jpg'):
  16. filename=os.path.split(file)[1].split('.')[0]
  17. #调用ocr识别
  18. apiname = 'ocr'
  19. rest =sg.apiSougouOcr(apiname,file)
  20. #调用身份证识别
  21. #rest =sg.apiSougouOcr('idcard',file)
  22. js= rest.json()
  23. retext =""
  24. if apiname=='ocr':
  25. #文字识别,rest应答包,字符串
  26. #成功 {"result":[{"content":"01245177\n","frame":["0,0","207,0","207,59","0,59"]}],"success":1}
  27. #失败 {"success":0}
  28. if js['success']==1 :
  29. retext = js['result'][0]['content'].strip()
  30. elif apiname == 'idcard':
  31. #身份证识别应答包,逼死强迫症啊,请求结构,应答结构都不一样
  32. '''
  33. {
  34. "result": {
  35. "住址": "xxxxxx",
  36. "公民身份号码": "11001xxx30",
  37. "出生": "19900101",
  38. "姓名": "xxXX",
  39. "性别": "X",
  40. "民族": "xxx"
  41. },
  42. "status": 0,
  43. "statusText": "Success"
  44. }
  45. '''
  46. if js['status']==0 :
  47. retext = js['result']['公民身份号码'].strip()
  48. print(filename,retext)

2、SougouAPI.py

  1. # -*- coding: utf-8 -*-
  2. # 搜狗API字典
  3. SougouAPI={
  4. #基本文本分析API
  5. "ocr": {
  6. 'APINAME':'图像识别', #API中文简称
  7. 'APIDESC': '识别图像中的文字', #API描述
  8. 'APIURL': 'http://api.ai.sogou.com/pub/ocr' #API请求URL
  9. },
  10. "idcard":{
  11. 'APINAME':'身份证识别', #API中文简称
  12. 'APIDESC': '身份证识别', #API描述
  13. 'APIURL': 'http://api.ai.sogou.com/pub/ocr/idcard' #API请求URL
  14. },
  15. }

3、SougouAPIMsg.py

  1. # -*- coding: utf-8 -*-
  2. '''
  3. create by : joshua zou
  4. create date : 2018.4.9
  5. Purpose: check sougou ai api
  6. '''
  7. import requests
  8. import base64
  9. import hashlib
  10. import hmac
  11. import time
  12. from urllib import parse
  13. import json
  14. from SougouAPI import *
  15. class SougouAPIMsg(object):
  16. def init(self,AppID=None,ApiKey=None,SecretKey=None):
  17. if not AppID: AppID = '88888'
  18. if not ApiKey: ApiKey = '5ADwS88888888Dtr6QG2'
  19. if not SecretKey: SecretKey= '0PLvS-AH8888888889n6NF6fVVTt7m'
  20. self.app_id= AppID
  21. self.app_key= ApiKey
  22. self.app_secret= SecretKey
  23. def get_time_stamp(self):
  24. return str(int(time.time()))
  25. '''
  26. 1、应用相关前缀 {AuthPrefix}
  27. {AuthPrefix}=sac-auth-v1/{accessKey}/{secondsSinceEpoch}/{expirationPeriodInSeconds}
  28. 2、请求相关数据 {Data}
  29. {Data}={REQUEST_METHOD} + "\n" + {HOST} + "\n" + {URI} + "\n" + {SORTED_QUERY_STRING}
  30. 其中,REQUEST_METHOD 为请求使用的 HTTP 方法, 如: GET|POST|PUT|DELETE
  31. HOST 为服务使用的域名, 如: api.ai.sogou.com
  32. URI 为请求的服务路径, 如: /speech/asr
  33. SORTED_QUERY_STRING 把 URL 中的 Query String(即 URL 中 “?” 后面的 “k1=v1&k2=v2” 字符串)进行编码后的结果。
  34. 编码方法为:
  35. 将 Query String 根据 & 拆开成若干项,对每一项转换为 UriEncode(key) + "=" + UriEncode(value) 的形式, 其中 value 可以是空字符串
  36. 将上面转换后的所有字符串按照字典顺序排序。
  37. 将排序后的字符串按顺序用 & 符号链接起来。
  38. 3、生成签名 {Signature}
  39. {Signature}=HMAC-SHA256-BASE64({secretKey}, {AuthPrefix} + "\n" + {Data})
  40. 4、生成认证信息, 通过 Authorization header 传递
  41. Authorization: {AuthPrefix}/{Signature}
  42. Example:
  43. 1\应用 accessKey/secretKey 分别为 bTkALtTB9x6GAxmFi9wetAGH / PMROwlieALT36qfdGClVz2iH4Sv8xZxe
  44. POST 方式访问 http://api.ai.sogou.com/speech/asr 接口
  45. GET 参数为 type=gbk&idx=1&starttime=1491810516
  46. 当前系统时间为 1491810516
  47. 2\计算过程
  48. {AuthPrefix}="sac-auth-v1/bTkALtTB9x6GAxmFi9wetAGH/1491810516/3600"
  49. {Data}="POST\napi.ai.sogou.com\n/speech/asr\nidx=1&starttime=1491810516&type=gbk"
  50. {Signature}=HMAC-SHA256-BASE64("PMROwlieALT36qfdGClVz2iH4Sv8xZxe", {AuthPrefix} + "\n" + {Data})="vuVEkzcnUeFv8FxeWS50c7S0HaYH1QKgtIV5xrxDY/s="
  51. 3\最终生成的 header 为
  52. Authorization: sac-auth-v1/bTkALtTB9x6GAxmFi9wetAGH/1491810516/3600/vuVEkzcnUeFv8FxeWS50c7S0HaYH1QKgtIV5xrxDY/s=
  53. '''
  54. def get_auth_sign_str(self,url,method):
  55. res= parse.urlparse(url)
  56. host= res.netloc
  57. uri = res.path
  58. query= res.query
  59. #1生成前置字符串
  60. authprefix= 'sac-auth-v1/%s/%s/%s' %(self.app_key,self.get_time_stamp(),3600)
  61. #2生成data
  62. query=dict( (k, v if len(v)>1 else v[0] )
  63. for k, v in parse.parse_qs(res.query).items() )
  64. sort_dict= sorted(query.items(), key=lambda item:item[0], reverse = False)
  65. sortquerystr= parse.urlencode(sort_dict)
  66. data= '%s\n%s\n%s\n%s' %(method,host,uri,sortquerystr)
  67. #3生成signstr
  68. signstr ='%s\n%s' %(authprefix,data)
  69. #调用hamc.sha256
  70. shastr =hmac.new(self.app_secret.encode(), signstr.encode(), digestmod=hashlib.sha256).digest()
  71. #base64编码,还原成字符串
  72. signature = base64.b64encode(shastr).decode()
  73. #4组合成最终的授权码
  74. authstr= '%s/%s' %(authprefix,signature)
  75. return authstr
  76. '''
  77. $file = "OCR-test03.jpg";
  78. $url = "http://api.ai.sogou.com/pub/ocr";
  79. $hdr = array(
  80. "Content-Type: multipart/form-data",
  81. "Authorization: ".sign($ak, $sk, $url, "POST")
  82. ); // cURL headers for file uploading
  83. $postfields = array(
  84. "pic" => curl_file_create($file,'image/jpeg','a_b_c.jpg'),
  85. );
  86. $ch = curl_init();
  87. $options = array(
  88. CURLOPT_URL => $url,
  89. CURLOPT_HEADER => false,
  90. CURLOPT_POST => 1,
  91. CURLOPT_HTTPHEADER => $hdr,
  92. CURLOPT_POSTFIELDS => $postfields,
  93. CURLOPT_RETURNTRANSFER => true
  94. );
  95. '''
  96. def apiSougouOcr(self,apiname,picfilename):
  97. url = SougouAPI[apiname]['APIURL']
  98. name = SougouAPI[apiname]['APINAME']
  99. desc= SougouAPI[apiname]['APIDESC']
  100. authstr=self.get_auth_sign_str(url, method='POST')
  101. header={ "Authorization": authstr }
  102. picfile= {'pic':open(picfilename,'rb')}
  103. resp = requests.post(url,headers=header,files=picfile)
  104. #print (resp.text)

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

pandas中的Dataframe查询有哪些方法

selenium+cookie跳过验证码登录实现步奏详解

以上就是python3下调用搜狗AI API的方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行