分享:利用网络函数调用百度文字识别API

阅读次数 534

以轻维表为例,使用POST函数 字段“图片”存储了用户上传的图片

//获取数据表的全部数据,fetchAllRecords是自定义函数,附后
//参数1是表的id.参数B是视图的id
const allRecords=fetchAllRecords(1,"B")
//遍历表的行记录,获取图片的uploadId,最终获取图片的url
allRecords.map(function(res){
    let picArr=res.fields.图片 //图片是字段名
    /*图片字段可以上传多张图片,所以picArr是包含了多个图片
    属性的对象数组,其中包含了一个key:uploadId,这就是我们
    需要的图片id
    */
    let id=picArr[0].uploadId
    //获取了第一张图片的id。多张图片可以使用循环 
    let picUrl=getUrl(id) //自定义函数
    let strText=OCR(picUrl) //自定义函数。这就是识别结果,返回JOSN结构的对象,根据自己的需求进一步处理
});

获取图片id后,使用GetAttachmentURL方法获取图片的url.这里使用一个自定义函数getUrl,参数是图片id

function getUrl(id){
  const resultURL=Application.Record.GetAttachmentURL({
    UploadId: id,
    Source: "upload_ks3" //这个参数一般是固定的
  });
  return(resultURL);
};

获取图片url之后,使用POST方法连接百度API

//POST方法有3个参数url,body,option
//返回识别结果
function OCR(picUrl){
  const strToken=getAccessToken();//自定义函数附后。这是百度文字识别url连接字符串必须的
  const url="https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + strToken;//accurate_basic高精度版,具体请查看百度文字识别API
  const Body={
    'url': picUrl,
    'language_type': 'CHN_ENG'
  };
  const Option={
    timeout:30000,
    headers:{
      'Content-Type': 'application/x-www-form-urlencoded',
      'content-type': 'multipart/form-data',
      'Accept':'application/json'
      }
  };
  let resp=HTTP.post(url,Body,Option);
  return(resp.json());
};

自定义函数,获取API请求必须的AccessToken

function getAccessToken(){
  const STR_AK ="这里填写你申请百度文字识别API时得到的API Key";
  const STR_SK = "这里填写你申请百度文字识别API时得到的Secret Key";
  var url="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + STR_AK + "&client_secret=" + STR_SK;
  let resp = HTTP.fetch(url,{
    method:"POST",
    timeout:2000,
    headers:{
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  });

自定义函数,获取表的所有行记录

function fetchAllRecords(sheetId,viewId) {
  let all = []
  let offset = null;

  while (all.length === 0 || offset) {
    let records = Application.Record.GetRecords({
      SheetId: sheetId,
      ViewId: viewId,
      Offset: offset
    })
    offset = records.offset
    all = all.concat(records.records)
  };
  return all;
};
1 Answers