python 3下捜犬AI API実現

19869 ワード

1、背景
a、捜犬も自分の人工知能apiを発表し、身分証明書ocr、名刺ocr、テキスト翻訳などのAPIを含め、初体験の正確率は一般的だ.
b、python 3に基づく.
c、自分の署名でこれを生成することもあります.ガチョウ工場の底があれば、比較的簡単に書けます.
d、しかしSougouは明らかにインタフェースの標準化のこの明らかにガチョウ工場に及ばないで、異なるapi応答パッケージの主体の構造は意外にも一致しないで、だから実施しても簡単な構造化だけをしました......
 
2、実現コード
直接コードを入れましょう.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]
        #  ocr  
        apiname = 'ocr'
        rest =sg.apiSougouOcr(apiname,file)
        #       
        #rest =sg.apiSougouOcr('idcard',file)
        

        js= rest.json()
        retext =""
        if apiname=='ocr':
            #    ,rest   ,   
            #    {"result":[{"content":"01245177
","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': # , , , ''' { "result": { " ": "xxxxxx", " ": "11001xxx30", " ": "19900101", " ": "xxXX", " ": "X", " ": "xxx" }, "status": 0, "statusText": "Success" } ''' if js['status']==0 : retext = js['result'][' '].strip() print(filename,retext)

 
2、SougouAPI.py
# -*- coding: utf-8 -*-
#   API  

SougouAPI={
    #      API
    "ocr":    {
        'APINAME':'    ', #API    
        'APIDESC': '        ', #API  
        'APIURL': 'http://api.ai.sogou.com/pub/ocr' #API  URL
    },
    "idcard":{
        'APINAME':'     ', #API    
        'APIDESC': '     ', #API  
        'APIURL': 'http://api.ai.sogou.com/pub/ocr/idcard' #API  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、       {AuthPrefix}
    {AuthPrefix}=sac-auth-v1/{accessKey}/{secondsSinceEpoch}/{expirationPeriodInSeconds}
    2、       {Data}        
    {Data}={REQUEST_METHOD} + "
" + {HOST} + "
" + {URI} + "
" + {SORTED_QUERY_STRING} ,REQUEST_METHOD HTTP , : GET|POST|PUT|DELETE HOST , : api.ai.sogou.com URI , : /speech/asr SORTED_QUERY_STRING URL Query String( URL “?” “k1=v1&k2=v2” ) 。 : Query String & , UriEncode(key) + "=" + UriEncode(value) , value 。 & 。 3、 {Signature} {Signature}=HMAC-SHA256-BASE64({secretKey}, {AuthPrefix} + "
" + {Data}) 4、 , Authorization header Authorization: {AuthPrefix}/{Signature} Example: 1\ accessKey/secretKey bTkALtTB9x6GAxmFi9wetAGH / PMROwlieALT36qfdGClVz2iH4Sv8xZxe POST http://api.ai.sogou.com/speech/asr GET type=gbk&idx=1&starttime=1491810516 1491810516 2\ {AuthPrefix}="sac-auth-v1/bTkALtTB9x6GAxmFi9wetAGH/1491810516/3600" {Data}="POST
api.ai.sogou.com
/speech/asr
idx=1&starttime=1491810516&type=gbk" {Signature}=HMAC-SHA256-BASE64("PMROwlieALT36qfdGClVz2iH4Sv8xZxe", {AuthPrefix} + "
" + {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
%s
%s
%s
' %(method,host,uri,sortquerystr) #3 signstr signstr ='%s
%s
' %(authprefix,data) # hamc.sha256 shastr =hmac.new(self.__app_secret.encode(), signstr.encode(), digestmod=hashlib.sha256).digest() #base64 , signature = base64.b64encode(shastr).decode() #4 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)

 
--以上--