python3下搜狗AI API實現

一、背景

a、搜狗也發佈了本身的人工智能 api,包括身份證ocr、名片ocr、文本翻譯等API,初試感受準確率通常般。python

b、基於python3。git

c、也有本身的簽名生成這塊,有了鵝廠的底子,相對寫起來比較簡單。github

d、不過Sougou明顯在接口標準化這塊明顯不如鵝廠,不一樣api應答包的主體結構居然不一致,因此實施也只作了簡單的結構化……json

 

二、實現代碼

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

一、sogouai-example.pyapp

# -*- 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\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':
            #身份證識別應答包,逼死強迫症啊,請求結構,應答結構都不同
            '''
            {
            "result": {
            "住址": "xxxxxx",
            "公民身份號碼": "11001xxx30",
            "出生": "19900101",
            "姓名": "xxXX",
            "性別": "X",
            "民族": "xxx"
            },
            "status": 0,
            "statusText": "Success"
            }
            '''
            if js['status']==0 :
                retext = js['result']['公民身份號碼'].strip()            
        print(filename,retext)

 

二、SougouAPI.pycurl

# -*- 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
    },
    
}

三、SougouAPIMsg.pypost

# -*- 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()))
    
    '''
    一、應用相關前綴 {AuthPrefix}
    {AuthPrefix}=sac-auth-v1/{accessKey}/{secondsSinceEpoch}/{expirationPeriodInSeconds}
    二、請求相關數據 {Data}        
    {Data}={REQUEST_METHOD} + "\n" + {HOST} + "\n" + {URI} + "\n" + {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 能夠是空字符串
    將上面轉換後的全部字符串按照字典順序排序。
    將排序後的字符串按順序用 & 符號連接起來。
    三、生成簽名 {Signature}        
     {Signature}=HMAC-SHA256-BASE64({secretKey}, {AuthPrefix} + "\n" + {Data})
    四、生成認證信息, 經過 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\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)
        #調用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)

 

-- 以上--編碼

相關文章
相關標籤/搜索