科大讯飞公式识别API接口PHP接入

科大讯飞公式识别API接口PHP接入

一、公式识别是什么?

公式识别是将图片(来源如扫描仪或数码相机)中的数学公式及题干,转换化为可编辑的标准LaTeX公式及文本。覆盖小学、初中、高中等多种题型,详细请参照 公式题型,目前仅支持拍照印刷体 。

二、使用步骤

1.注册并认证

访问讯飞官网注册账号:https://xinghuo.xfyun.cn/sparkapi?ch=gji
在这里插入图片描述
服务管理-完成个人认证
在这里插入图片描述

2.创建应用

右上角-我的应用
在这里插入图片描述
完善应用信息
在这里插入图片描述
左边选择“文字识别”-“公式识别”
在这里插入图片描述
右边的token信息需要记录下来,后面要用

3.构建API

https://www.xfyun.cn/doc/words/formula-discern/API.html
官方提供的demo有python3、java、nodejs、php语言,这里以PHP为例构建一个API
index.php获取待识别的图片,存储到本地调用,识别完成后删除图片。

<?php
/**
 * 公式识别 WebAPI 接口调用示例
 * 运行前:请先填写Appid、APIKey、APISecret
 * 
 * 1.接口文档(必看):https://www.xfyun.cn/doc/words/formula-discern/API.html
 * 2.错误码链接:https://www.xfyun.cn/document/error-code (错误码code为5位数字)
 * @author iflytek
 */
 
 
class itr_teach_test {
    function tocurl($url, $header, $content){
        $ch = curl_init();
        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        if (is_array($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        if (!empty($content)) {
            if (is_array($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
            } else if (is_string($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
            }
        }
        $response = curl_exec($ch);
        $error=curl_error($ch);
        //var_dump($error);
        if($error){
            die($error);
        }
        $header = curl_getinfo($ch);
 
        curl_close($ch);
        $data = array('header' => $header,'body' => $response);
        return $data;
    }
    function xfyun($pic,$jpg) {
		//在控制台-我的应用-公式识别获取
        $app_id = "xxxxxx";
		//在控制台-我的应用-公式识别获取
        $api_sec = "xxxxxx";
		//在控制台-我的应用-公式识别获取
        $api_key = "xxxxxx";
		//图片路径
        $resource = $jpg;
 
        $url = "https://rest-api.xfyun.cn/v2/itr";
 
        //body组装
        $body = json_encode($this->getBody($app_id,  $resource));
 
        // 组装http请求头
        //$date = gmstrftime("%a, %d %b %Y %H:%M:%S %Z", time());
		$date =gmdate('D, d M Y H:i:s') . ' GMT';
		
        $digestBase64  = "SHA-256=".base64_encode(hash("sha256", $body, true));
		
        $builder = sprintf("host: %s
date: %s
POST /v2/itr HTTP/1.1
digest: %s", "rest-api.xfyun.cn", $date, $digestBase64);
 
        $sha = base64_encode(hash_hmac("sha256", $builder, $api_sec, true));
 
        $authorization = sprintf("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", $api_key, "hmac-sha256", "host date request-line digest", $sha);
 
        $header = [
            "Authorization: ".$authorization,
            'Content-Type: application/json',
            'Accept: application/json,version=1.0',
            'Host: rest-api.xfyun.cn',
            'Date: '.$date,
            'Digest: '.$digestBase64
        ];
 
        $response = $this->tocurl($url, $header, $body);
 
        //var_dump($response['body']);
        $res = json_decode($response['body'], true);//转换为数组
        $content = $res['data']['region'][0]['recog']['content'];
        $content = str_replace("  ", "", $content);
        $content = str_replace("ifly-latex-begin", "", $content);
        $content = str_replace("ifly-latex-end", "", $content);
        header("content-type: application/json");
        if($res['code']=='0'){
            $code='200';
        }else{
            $code='202';
        }
        $json_return = array(
            "code" => $code,
            "src" => $pic,
            "dst" => ltrim($content)
        );
        $result = json_encode($json_return, JSON_UNESCAPED_UNICODE);
        echo $result;
    }
 
    function getBody($app_id, $resource) {
        $common_param = [
            'app_id'   => $app_id
        ];
        $image_data = fread(fopen($resource, 'r'), filesize($resource));
        $base64_image = chunk_split(base64_encode($image_data));
 
        $data = [
            'image' => $base64_image
        ];
 
        return $body = [
            'common' => $common_param,
            'business' => [
                'ent' => 'teach-photo-print',
                'aue'      => 'raw'
            ],
            'data' => $data
        ];
    }
}
 
/*
*@通过curl方式获取指定的图片到本地
*@ 完整的图片地址
*@ 要存储的文件名
*/
function getImg($url = "", $filename = ""){
    //去除URL连接上面可能的引号
    $hander = curl_init();
    $fp = fopen($filename, 'wb');
    curl_setopt($hander, CURLOPT_URL, $url);
    curl_setopt($hander, CURLOPT_FILE, $fp);
    curl_setopt($hander, CURLOPT_HEADER, 0);
    curl_setopt($hander, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($hander, CURLOPT_TIMEOUT, 60);
    curl_exec($hander);
    curl_close($hander);
    fclose($fp);
    return true;
}
 
header('Access-Control-Allow-Origin:*');
header('Content-type: application/json');
 
$pic=isset($_GET['pic'])? $_GET['pic'] :null; 
if(empty($pic)){die("请传入图片参数");}
$time = gmdate('H-i-s', time() + 3600 * 8);   
$jpg = $time.'.jpg';
getImg($pic,$jpg);
 
$a = new itr_teach_test();
$a->xfyun($pic,$jpg);
unlink($jpg);

运行前:请先填写Appid、APIKey、APISecret

4.调用实例

比如需识别该公式
在这里插入图片描述
请求地址:

https://你的api地址/?pic=待识别图片网络地址

返回数据:

{
   "code": "200",
   "src": "待识别图片网络地址",
   "dst": "\\frac {x^ {2}}{a^ {2}}  -  \\frac {y^ {2}}{b^ {2}}  =1(a>0,b>0)"
}

Demo:https://api.szfx.top/api/itr.html


总结

以上就是使用科大讯飞公式识别API接口PHP接入的教程,欢迎大家去体验。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值