python3下實(shí)現(xiàn)搜狗AI API的代碼示例
1、背景
a、搜狗也發(fā)布了自己的人工智能 api,包括身份證ocr、名片ocr、文本翻譯等API,初試感覺(jué)準(zhǔn)確率一般般。
b、基于python3。
c、也有自己的簽名生成這塊,有了鵝廠的底子,相對(duì)寫(xiě)起來(lái)比較簡(jiǎn)單。
d、不過(guò)Sougou明顯在接口標(biāo)準(zhǔn)化這塊明顯不如鵝廠,不同api應(yīng)答包的主體結(jié)構(gòu)竟然不一致,所以實(shí)施也只做了簡(jiǎn)單的結(jié)構(gòu)化……
2、實(shí)現(xiàn)代碼
直接放代碼吧,github上也有: https://github.com/jdstkxx/PySougouAI
1、sogouai-example.py
# -*- coding: utf-8 -*-
'''
create by : joshua zou
create date : 2018.4.9
Purpose: check sougou ai api
'''
import glob,os
from SougouAPIMsg import *
#改成你自己搜狗AI的APPID、APPKEY、SecretKey
AppID = '0000'
ApiKey = '*********'
SecretKey= '0PLvS-AHShmq**************'
if __name__ == "__main__":
sg = SougouAPIMsg(AppID,ApiKey,SecretKey)
for file in glob.glob('D:\python\*.jpg'):
filename=os.path.split(file)[1].split('.')[0]
#調(diào)用ocr識(shí)別
apiname = 'ocr'
rest =sg.apiSougouOcr(apiname,file)
#調(diào)用身份證識(shí)別
#rest =sg.apiSougouOcr('idcard',file)
js= rest.json()
retext =""
if apiname=='ocr':
#文字識(shí)別,rest應(yīng)答包,字符串
#成功 {"result":[{"content":"01245177\n","frame":["0,0","207,0","207,59","0,59"]}],"success":1}
#失敗 {"success":0}
if js['success']==1 :
retext = js['result'][0]['content'].strip()
elif apiname == 'idcard':
#身份證識(shí)別應(yīng)答包,逼死強(qiáng)迫癥啊,請(qǐng)求結(jié)構(gòu),應(yīng)答結(jié)構(gòu)都不一樣
'''
{
"result": {
"住址": "xxxxxx",
"公民身份號(hào)碼": "11001xxx30",
"出生": "19900101",
"姓名": "xxXX",
"性別": "X",
"民族": "xxx"
},
"status": 0,
"statusText": "Success"
}
'''
if js['status']==0 :
retext = js['result']['公民身份號(hào)碼'].strip()
print(filename,retext)
2、SougouAPI.py
# -*- coding: utf-8 -*-
# 搜狗API字典
SougouAPI={
#基本文本分析API
"ocr": {
'APINAME':'圖像識(shí)別', #API中文簡(jiǎn)稱
'APIDESC': '識(shí)別圖像中的文字', #API描述
'APIURL': 'http://api.ai.sogou.com/pub/ocr' #API請(qǐng)求URL
},
"idcard":{
'APINAME':'身份證識(shí)別', #API中文簡(jiǎn)稱
'APIDESC': '身份證識(shí)別', #API描述
'APIURL': 'http://api.ai.sogou.com/pub/ocr/idcard' #API請(qǐng)求URL
},
}
3、SougouAPIMsg.py
# -*- coding: utf-8 -*-
'''
create by : joshua zou
create date : 2018.4.9
Purpose: check sougou ai api
'''
import requests
import base64
import hashlib
import hmac
import time
from urllib import parse
import json
from SougouAPI import *
class SougouAPIMsg(object):
def __init__(self,AppID=None,ApiKey=None,SecretKey=None):
if not AppID: AppID = '88888'
if not ApiKey: ApiKey = '5ADwS88888888Dtr6QG2'
if not SecretKey: SecretKey= '0PLvS-AH8888888889n6NF6fVVTt7m'
self.__app_id= AppID
self.__app_key= ApiKey
self.__app_secret= SecretKey
def get_time_stamp(self):
return str(int(time.time()))
'''
1、應(yīng)用相關(guān)前綴 {AuthPrefix}
{AuthPrefix}=sac-auth-v1/{accessKey}/{secondsSinceEpoch}/{expirationPeriodInSeconds}
2、請(qǐng)求相關(guān)數(shù)據(jù) {Data}
{Data}={REQUEST_METHOD} + "\n" + {HOST} + "\n" + {URI} + "\n" + {SORTED_QUERY_STRING}
其中,REQUEST_METHOD 為請(qǐng)求使用的 HTTP 方法, 如: GET|POST|PUT|DELETE
HOST 為服務(wù)使用的域名, 如: api.ai.sogou.com
URI 為請(qǐng)求的服務(wù)路徑, 如: /speech/asr
SORTED_QUERY_STRING 把 URL 中的 Query String(即 URL 中 “?” 后面的 “k1=v1&k2=v2” 字符串)進(jìn)行編碼后的結(jié)果。
編碼方法為:
將 Query String 根據(jù) & 拆開(kāi)成若干項(xiàng),對(duì)每一項(xiàng)轉(zhuǎn)換為 UriEncode(key) + "=" + UriEncode(value) 的形式, 其中 value 可以是空字符串
將上面轉(zhuǎn)換后的所有字符串按照字典順序排序。
將排序后的字符串按順序用 & 符號(hào)鏈接起來(lái)。
3、生成簽名 {Signature}
{Signature}=HMAC-SHA256-BASE64({secretKey}, {AuthPrefix} + "\n" + {Data})
4、生成認(rèn)證信息, 通過(guò) Authorization header 傳遞
Authorization: {AuthPrefix}/{Signature}
Example:
1\應(yīng)用 accessKey/secretKey 分別為 bTkALtTB9x6GAxmFi9wetAGH / PMROwlieALT36qfdGClVz2iH4Sv8xZxe
POST 方式訪問(wèn) http://api.ai.sogou.com/speech/asr 接口
GET 參數(shù)為 type=gbk&idx=1&starttime=1491810516
當(dāng)前系統(tǒng)時(shí)間為 1491810516
2\計(jì)算過(guò)程
{AuthPrefix}="sac-auth-v1/bTkALtTB9x6GAxmFi9wetAGH/1491810516/3600"
{Data}="POST\napi.ai.sogou.com\n/speech/asr\nidx=1&starttime=1491810516&type=gbk"
{Signature}=HMAC-SHA256-BASE64("PMROwlieALT36qfdGClVz2iH4Sv8xZxe", {AuthPrefix} + "\n" + {Data})="vuVEkzcnUeFv8FxeWS50c7S0HaYH1QKgtIV5xrxDY/s="
3\最終生成的 header 為
Authorization: sac-auth-v1/bTkALtTB9x6GAxmFi9wetAGH/1491810516/3600/vuVEkzcnUeFv8FxeWS50c7S0HaYH1QKgtIV5xrxDY/s=
'''
def get_auth_sign_str(self,url,method):
res= parse.urlparse(url)
host= res.netloc
uri = res.path
query= res.query
#1生成前置字符串
authprefix= 'sac-auth-v1/%s/%s/%s' %(self.__app_key,self.get_time_stamp(),3600)
#2生成data
query=dict( (k, v if len(v)>1 else v[0] )
for k, v in parse.parse_qs(res.query).items() )
sort_dict= sorted(query.items(), key=lambda item:item[0], reverse = False)
sortquerystr= parse.urlencode(sort_dict)
data= '%s\n%s\n%s\n%s' %(method,host,uri,sortquerystr)
#3生成signstr
signstr ='%s\n%s' %(authprefix,data)
#調(diào)用hamc.sha256
shastr =hmac.new(self.__app_secret.encode(), signstr.encode(), digestmod=hashlib.sha256).digest()
#base64編碼,還原成字符串
signature = base64.b64encode(shastr).decode()
#4組合成最終的授權(quán)碼
authstr= '%s/%s' %(authprefix,signature)
return authstr
'''
$file = "OCR-test03.jpg";
$url = "http://api.ai.sogou.com/pub/ocr";
$hdr = array(
"Content-Type: multipart/form-data",
"Authorization: ".sign($ak, $sk, $url, "POST")
); // cURL headers for file uploading
$postfields = array(
"pic" => curl_file_create($file,'image/jpeg','a_b_c.jpg'),
);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $hdr,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_RETURNTRANSFER => true
);
'''
def apiSougouOcr(self,apiname,picfilename):
url = SougouAPI[apiname]['APIURL']
name = SougouAPI[apiname]['APINAME']
desc= SougouAPI[apiname]['APIDESC']
authstr=self.get_auth_sign_str(url, method='POST')
header={ "Authorization": authstr }
picfile= {'pic':open(picfilename,'rb')}
resp = requests.post(url,headers=header,files=picfile)
#print (resp.text)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django中文件上傳和文件訪問(wèn)微項(xiàng)目的方法
這篇文章主要介紹了Django中文件上傳和文件訪問(wèn)微項(xiàng)目的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04
基于Python實(shí)現(xiàn)文章信息統(tǒng)計(jì)的小工具
及時(shí)的統(tǒng)計(jì)可以更好的去分析讀者對(duì)于內(nèi)容的需求,了解文章內(nèi)容的價(jià)值,以及從側(cè)面認(rèn)識(shí)自己在知識(shí)創(chuàng)作方面的能力。本文就來(lái)用Python制作一個(gè)文章信息統(tǒng)計(jì)的小工具?,希望對(duì)大家有所幫助2023-02-02
Python實(shí)現(xiàn)的多線程http壓力測(cè)試代碼
這篇文章主要介紹了Python實(shí)現(xiàn)的多線程http壓力測(cè)試代碼,結(jié)合實(shí)例形式分析了Python多線程操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-02-02
Python?常用的print輸出函數(shù)和input輸入函數(shù)
這篇文章主要介紹了Python?常用的print輸出函數(shù)和input輸入函數(shù),今天主要學(xué)習(xí)一下Python中的輸入輸出流,會(huì)對(duì)標(biāo)準(zhǔn)輸入輸出流、文件輸入輸出流展開(kāi)介紹,需要的朋友可以參考一下2022-02-02
Python后臺(tái)管理員管理前臺(tái)會(huì)員信息的講解
今天小編就為大家分享一篇關(guān)于Python后臺(tái)管理員管理前臺(tái)會(huì)員信息的講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01
在Sublime Editor中配置Python環(huán)境的詳細(xì)教程
這篇文章主要介紹在sublime編輯器中安裝python軟件包,以 實(shí)現(xiàn)自動(dòng)完成等功能,并在sublime編輯器本身中運(yùn)行build,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2020-05-05
python3.7.2 tkinter entry框限定輸入數(shù)字的操作
這篇文章主要介紹了python3.7.2 tkinter entry框限定輸入數(shù)字的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05

