【应⽤】PHP调⽤百度⽂档翻译接⼝
的⽂档是需要消费的,并且它的api请求是⼀个异步的过程,如果业务上⽤户不需要登录的时候,⽆法直接获取到翻译结果⽂档。因此,做了个异步返回的功能。
思路:
1、上传⽂档;
2、调⽤翻译接⼝;
3、通过kafka监听接⼝回调,处理返回数据,保存到本地(⽅便以后扩展,如加⼊⽤户信息,查看我的翻译记录)
4、前端监听后端服务,通过swoole的websocket实时请求⽂档数据
关键部分代码(赶⼯做的,未做优化):
//上传⽂件
public function upload()
{
header("Access-Control-Allow-Origin:*");
set_time_limit(300);
$file = $_FILES['file'];
if(!$file){
$show = array('status'=>422,'message'=>'请上传图⽚或者⽂档⽂件');
json($show);
}
$app = '2020bd';
if($_SERVER['SERVER_ADDR']=='127.0.0.1'){
$sPath = '/Users/kunyuan/www/activity/storage/'.$app.'/';
}else{
$sPath = '/var/www/html/activity/storage/'.$app.'/';
}
if(!mk_dir($sPath)){
$show = array('status'=>500,'message'=>'⽬录不存在');
json($show);
}
$path_parts = pathinfo($file['name']);
$ext = strtolower($path_parts["extension"]);
$extAry = array(
'jpg','jpeg','png','docx','xls','xlsx','ppt','pptx','pdf'
)
;
if(!in_array($ext, $extAry)){
$show = array('status'=>422,'message'=>'请上传图⽚或者⽂档⽂件');
json($show);
}
try{
//保存到服务器本地
$filename = date('Ymd'). '_' .rand(10000, 99999).'_'.time();
$tmpfile = $filename . '.'.$ext;
$tmp = $file["tmp_name"];
$img = file_get_contents($tmp);
$path1 = $sPath . $tmpfile;
$res = file_put_contents($path1, $img);
if(is_https()){
$url = ''.$_SERVER['SERVER_NAME'].'/storage/'.$app.'/'.$tmpfile;
}else{
$url = ''.$_SERVER['SERVER_NAME'].'/storage/'.$app.'/'.$tmpfile;
}
}
$error = '上传失败';
if($res){
//判断⽂件类型,为了⽂件调⽤百度的图⽚接⼝或者⽂档接⼝
if(in_array($ext,array('jpg','jpeg','png'))){
$resExt = 'pic';
}else{
$resExt = 'docs';
}
//保存数据库
$fileid = $this->common->setFiles(array(
'sourceFile' => $url,
'localFile' => $path1,
'type' => $resExt
));
$show = array('status'=>0,'fileUrl'=>$url,'fileSize'=>ceil(filesize($path1)/1000)."k",'ext'=>$resExt, 'id' => $fileid,'resExt'=>$resExt); }else{
$show = array('status'=>500,'message'=>$error,'info'=>$info,'fileSize'=>ceil(filesize($path1)/1000)."k");
}
json($show);
}catch(Exception $e){
$show = array('status'=>$e->getCode(),'message'=>$e->getMessage());
json($show);
}
}
//调⽤百度接⼝
public function api()
{
//$type = I('type','docs');
$id = I('id',0);
$callback = I('callback');
//判断是否为上传的⽂件
$data = $this->common->getFiles(array('id'=>$id));
if(empty($data)){
$show = array('status'=>420,'message'=>'数据有误');
json($show, $callback);
}
$type = $data['type'];
switch($type){
case 'docs':
$this->docsTran($data);
break;
case 'pic':
$this->picTran($data);
break;
default:
$this->docsTran($data);
break;
}
}
//⽂档翻译接⼝
private function docsTran($data)
{
//die('ooo');
$file = $data['localFile'];//I('file');
$from = I('from', 'zh');
$to = I('to','en');
$callback = I('callback');
$callback = I('callback');
if(empty($file)){
$show = array('status'=>422,'message'=>'请上传⽂档⽂件');
json($show, $callback);
}
$path_parts = pathinfo($file);
$ext = strtolower($path_parts["extension"]);
$extAry = array(
'docx','xls','xlsx','ppt','pptx','pdf'
);
if(!in_array($ext, $extAry)){
$show = array('status'=>423,'message'=>'请上传⽂档⽂件');
json($show, $callback);
}
if($from == $to){
$show = array('status'=>424,'message'=>'翻译语⾔不能与原⽂档⾔语⼀样'); json($show, $callback);
}
$arr = array(
'requestId' => uniqid(),
'sourceFile' => $data['sourceFile'],
'localFile' => '',
'type' => 'docs',
'content' => '',
'create_time' => time()
);
$id = $this->common->set($arr);
$params = array(
'appid' => $this->appid, //你的appid
'from' => $from,
'to' => $to,
'timestamp' => time(), //10位时间戳
'type' => $ext, //⽂档类型,根据具体⽂档⽽定
);
$seckey = $this->seckey; //你的密钥
ksort($params);
$querySign = '';
foreach ($params as $key => $value) {
$querySign .= $key . '=' . $value . '&';
}
$filePath = $file; //⽂档路径
$params['sign'] = md5($querySign . '' . md5_file($filePath) . '' . $seckey);
$url = 'fanyi-api.baidu/api/trans/vip/doctrans';
$header = array(
'Content-Type' => 'multipart/form-data',
);
$params['file'] = '@' . realpath($imagePath);
/
/⾼版本兼容
if (class_exists('\CURLFile')) {
$params['file'] = new \CURLFile(realpath($filePath));
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
curl_close($ch);
logs('Docs Result>>>'.$result);
$callRet = json_decode($result, true);
//print_R($result);
if($callRet['error_code'] == 52000){
$arr = array(
'requestId' => $callRet['data']['requestId'],
);
$this->common->update($arr, array('id'=>$id));
/
/$this->load->libraliry('Kafka');
$this->kafkaMsg($callRet['data']['requestId']);
$show = array('status'=>0,'message'=>'翻译成功','requestId'=>$callRet['data']['requestId']);
json($show, $callback);
}else{
$show = array('status'=>$callRet['error_code'],'message'=>$callRet['error_msg']);
json($show, $callback);
}
}
//图⽚翻译接⼝
private function picTran($data)
{
$file = $data['localFile'];//I('file');
//echo $file;
$from = I('from', 'zh');
$to = I('to','en');
$callback = I('callback');
if(empty($file)){
$show = array('status'=>422,'message'=>'请上传图⽚⽂件');
json($show, $callback);
}
$path_parts = pathinfo($file);
$ext = strtolower($path_parts["extension"]);
$extAry = array(
'jpg','jpeg','png'
);
if(!in_array($ext, $extAry)){
$show = array('status'=>423,'message'=>'请上传图⽚⽂件');
json($show, $callback);
}
if($from == $to){
$show = array('status'=>424,'message'=>'翻译语⾔不能与原⽂件⾔语⼀样');
json($show, $callback);
}
$appid = $this->appid;
$salt = rand();
$cuid = 'APICUID';
$mac = 'MAC';
$secKey = $this->seckey;
$imagePath = $file;
//echo $imagePath;
$sign = md5($appid . md5(file_get_contents($imagePath)) . $salt . $cuid . $mac . $secKey);
$url = 'fanyi-api.baidu/api/trans/sdk/picture?appid=' . $this->appid . '&from=' . $from . '&to=' . $to . '&salt=' . $salt . '&cuid=' . $cuid . '&mac=' . $mac . '& $header = array(
'Content-Type' => 'multipart/form-data',
'Content-Type' => 'multipart/form-data',
);
$sendData = array(
'image' => '@' . realpath($imagePath) . ';type=image/jpeg',
);
if (class_exists('\CURLFile')) {
$sendData['image'] = new \CURLFile(realpath($imagePath));
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$sendData);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
logs('PIC Result>>>'.$result);
$callRet = json_decode($result, true);
//print_R($callRet);
if($callRet['error_code'] == 0){
$arr = array(
'requestId' => uniqid(),
'sourceFile' => $data['sourceFile'],
'localFile' => $file,
'type' => 'pic',
'content' => $callRet['data']['sumSrc'],
'create_time' => time()
);
//print_r($arr);
$this->common->set($arr);
$show = array('status'=>0,'message'=>'翻译成功','srcContent'=>$callRet['data']['sumSrc'] ,'tranContent' => $callRet['data']['sumDst']); json($show, $callback);
}else{
$show = array('status'=>$callRet['error_code'],'message'=>$callRet['error_msg']);
json($show, $callback);
}
}
//消息⽣产
private function kafkaMsg($requestId)
{
$topicname = "testlin";
logs('kafkaMsgStart>>>' . $requestId . '>>' . $topicname);
$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'localhost:9092');
$producer = new RdKafka\Producer($conf);
$topic = $producer->newTopic($topicname);
$topic->produce(RD_KAFKA_PARTITION_UA, 0, $requestId);
//$producer->poll(0);
$result = $producer->flush(1000);
if (RD_KAFKA_RESP_ERR_NO_ERROR !== $result) {
logs('ERROR>>>' . 'Was unable to flush, messages might be lost!');百度api接口
}
logs('kafkaMsgEnd>>>' . $requestId);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论