百度ai sdk php,PHP如何调用百度AI开放平台中NLP语言处理基础技术的“依存句法分析”等接口?...

《PHP如何调用百度AI开放平台中NLP语言处理基础技术的“依存句法分析”等接口?》要点:

本文介绍了PHP如何调用百度AI开放平台中NLP语言处理基础技术的“依存句法分析”等接口?,希望对您有用。如果有疑问,可以联系我们。

相关主题:PHP开发

在百度AI开放平台中,PHP如何调用NLP语言处理基础技术等接口?

有两种模式:

一种是使用百度的SDK,参http://ai.baidu.com/docs#/NLP-PHP-SDK/fddb1eac

一种是使用自己封装的PHP类,参http://ai.baidu.com/docs#/NLP-API/top

本例展示了使用自己封装的PHP类调用百度NLP的句法依存关系接口:/**

* Class baiduapi  不使用

* 作者:www.vephp.com

*/

class baiduapi

{

public $error ='';

public $apiUrl = '';

private $_errnum=1;

private $header = ["Content-Type: application/json"];

public $access_token='';

//以下这些需要换成你自己的。

public $appId1 = '2321332';

public $appKey1 = 'WLsd3232bI1j7ve3rnCNHIf';  //换成你的APP KEYA

public $appSecretKey1 = 'f8w4g123asdfjwP0AExcYFh17PhLjYt1';  //换成你的

public $tokenApi = 'https://aip.baidubce.com/oauth/2.0/token';

public $grant_type = 'client_credentials';

//缓存文件路径

public $cacheFile = WEBROOT.'public/uploads/modules/tmp';

/**

* http constructor.

*/

public function __construct ()

{

if(!is_dir ($this->cacheFile)) @mkdir ($this->cacheFile);

$this->cacheFile = $this->cacheFile.'/baiduapi_token_cache.txt';

$this->access_token = $this->getAccessToken ();

}

/**

* 依存句法分析接口

* @param $mode 默认值为0,可选值mode=0(对应web模型,适用于处理网页文本等书面表达句子);mode=1(对应query模型,适用于处理信息需求类的搜索或口语query)

*/

public function textDependParse($text='', $mode =0)

{

$this->apiUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/depparser?charset=UTF-8&access_token='.$this->access_token;

$post = ['text'=>$text, 'mode'=>$mode];   // mb_convert_encoding(json_encode($text), 'GBK', 'UTF8')

$post = json_encode ($post);  #关键

$re = $this->getBaiduApi($this->apiUrl, $post , $this->header);

return $re;

}

/** 获取百度API接口返回值:

* @param $url API地址,如拼音调用,

* @param string $auth  你在百度的apiKey

* @return mixed 成功则返回std对象

*/

public function getBaiduApi($url='', $postData='', $headers=[])

{

if(empty($url)) return false;

$ch = curl_init ();

curl_setopt ( $ch, CURLOPT_URL, $url );

#["apikey: $apiKeyAuth"]

if(!empty($headers)) curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );

curl_setopt ( $ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_TIMEOUT, 10);  //cURL允许执行的最长秒数。这里设定10S

curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);

curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

#curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt ( $ch, CURLOPT_POST, empty($postData)?0:1 );  //POST则设置为1

if(!empty($postData) ){

if( is_array ($postData)) $postData = http_build_query($postData);

curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postData );  //POST方式再启用

}

$result = curl_exec ( $ch );

curl_close ( $ch );

$result = json_decode($result);

if( $this-> _errorParse($result))

{

if(($result->error_code=='111' || $result->error_code=='110') && $this->_errnum++==1) //Access token过期,重新请求一次

{

if(file_exists ($this->cacheFile)) @unlink ($this->cacheFile);

$newAccessToken = $this->getAccessToken ();

$this->apiUrl = str_replace ($this->access_token,$newAccessToken,$this->apiUrl);

$url = str_replace ($this->access_token,$newAccessToken, $url);

$this->access_token =$newAccessToken;

unset($newAccessToken);

$result = $this->getBaiduApi($url, $postData, $headers);

}else{

return false;

}

}

return $result;

}

/** 获取 access token

* @return mixed

*/

public function getAccessToken()

{

$cacheFile = file_exists ($this->cacheFile) ? file_get_contents ($this->cacheFile) : '';

if(!empty($cacheFile))

{

$json = json_decode ($cacheFile);

if( (time ()-$json->starttime) expires_in-100) ) return $json->access_token;  #2592000

}

$post_data['grant_type']       = $this->grant_type;

$post_data['client_id']      = $this->appKey1;

$post_data['client_secret'] = $this->appSecretKey1;

$paraStr = "";

foreach ( $post_data as $k => $v )     {

$paraStr .= "$k=" . urlencode( $v ). "&" ;

}

$paraStr = substr($paraStr ,0,-1);

$this->apiUrl = 'https://aip.baidubce.com/oauth/2.0/token';

$this->apiUrl .='?'.$paraStr;

#$url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=WL3EGcTOnbI1j7ve3rnCNHIf&client_secret=f8w4gG5GdLLMjwP0AExcYFh17PhLjYt1';

$res = $this->getBaiduApi($this->apiUrl);

if(!empty($this->error)){

return false;

}

$res->starttime = time ();

file_put_contents ($this->cacheFile ,json_encode ($res, true));

return  $res->access_token;

}

private function _errorParse($res)

{

$errors=[

'1'=> 'Unknown error  服务器内部错误,请再次请求,如果持续出现此类错误,请通过QQ群(224994340)或工单联系技术支持团队',

'2'=>'Service temporarily unavailable  服务暂不可用,请再次请求,如果持续出现此类错误,请通过QQ群(224994340)或工单联系技术支持团队',

'3'=>'Unsupported openapi method  调用的API不存在,请检查后重新尝试',

'4'=>'Open api request limit reached  集群超限额',

'6'=>'No permission to access data  无权限访问该用户数据',

'17'=>'Open api daily request limit reached  每天请求量超限额',

'18'=>'Open api qps request limit reached      QPS超限额',

'19'=>'Open api total request limit reached  请求总量超限额',

'100'=>'Invalid parameter  包含了无效或错误参数,请检查代码',

'110'=>'Access token invalid or no longer valid: Access Token失效',

'111'=>'Access token expired: Access token过期',

'282000'=>'internal error  服务器内部错误,请再次请求, 如果持续出现此类错误,请通过QQ群(632426386)或工单联系技术支持团队。',

'282002'=>'input encoding error        编码错误,请使用GBK编码',

'282004'=>'invalid parameter(s) 请求中包含非法参数,请检查后重新尝试',

'282130'=>'no result   当前查询无结果返回,出现此问题的原因一般为:参数配置存在问题,请检查后重新尝试',

'282131'=>'input text too long  输入长度超限,请查看文档说明',

'282133'=>'param {参数名} not exist       接口参数缺失',

'282300'=>'word error: word不在算法词典中',

'282301'=>'word_1 error        word_1 提交的词汇暂未收录,无法比对相似度',

'282302'=>'word_2 error: word_2 提交的词汇暂未收录,无法比对相似度',

'282303'=>'word_1&word_2 error : word_1和word_2暂未收录,无法比对相似度',

];

$this->error = '';

if (!empty($res->error_code) && !empty($errors[$res->error_code]))

{

$this->error = $errors[$res->error_code];

}

return  !empty($this->error) ? $this->error  : false;

}

}

调用示例:

$re = $baidu->textDependParse('3D滚轮瘦脸仪微电流V脸神器脸部按摩器提拉紧致面部按摩仪美容仪');

if(!$re) echo $baidu->error;

else print_r ($re);