|
|
|
@ -0,0 +1,76 @@
|
|
|
|
|
package ai_model_cli
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"goskeleton/app/global/my_errors"
|
|
|
|
|
"goskeleton/app/global/variable"
|
|
|
|
|
"goskeleton/app/utils/baidubce"
|
|
|
|
|
"goskeleton/app/utils/files"
|
|
|
|
|
"net/http"
|
|
|
|
|
"net/url"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 向百度智能云ocr(基础精准版)发送消息, 获得识别消息
|
|
|
|
|
* @return 识别出的信息的内容
|
|
|
|
|
*/
|
|
|
|
|
func RequestOCR(context *gin.Context) (r bool, c interface{}) {
|
|
|
|
|
path := "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + baidubce.GetAccessToken()
|
|
|
|
|
// 获得图片数据,需要 base64 和urlencode处理
|
|
|
|
|
// linlnf: test
|
|
|
|
|
content, _ := files.GetFileBase64("storage/app/test/文字识别.png")
|
|
|
|
|
// 组装 body 数据,参数在该网址:https://cloud.baidu.com/doc/OCR/s/1k3h7y3db
|
|
|
|
|
data := make(url.Values)
|
|
|
|
|
data.Set("detect_direction", "false")
|
|
|
|
|
data.Set("paragraph", "false")
|
|
|
|
|
data.Set("probability", "false")
|
|
|
|
|
data.Set("multidirectional_recognize", "false")
|
|
|
|
|
data.Set("image", content)
|
|
|
|
|
payload := strings.NewReader(data.Encode())
|
|
|
|
|
client := &http.Client{}
|
|
|
|
|
// 请求数据
|
|
|
|
|
req, err := http.NewRequest("POST", path, payload)
|
|
|
|
|
if err != nil {
|
|
|
|
|
variable.ZapLog.Error(my_errors.ErrorBaiduCEUseOCRFail + err.Error())
|
|
|
|
|
return false, nil
|
|
|
|
|
}
|
|
|
|
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
|
req.Header.Add("Accept", "application/json")
|
|
|
|
|
res, err := client.Do(req)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
variable.ZapLog.Error(my_errors.ErrorBaiduCEUseOCRFail + err.Error())
|
|
|
|
|
return false, nil
|
|
|
|
|
}
|
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
//从res中提取识别出的字符信息
|
|
|
|
|
mbody, err := baidubce.DecodeResBody(res, "ocr")
|
|
|
|
|
if err != nil {
|
|
|
|
|
variable.ZapLog.Error(my_errors.ErrorBaiduCEUseOCRFail + err.Error())
|
|
|
|
|
return false, nil
|
|
|
|
|
}
|
|
|
|
|
return true, gin.H{
|
|
|
|
|
"words": decodeBody2Str(mbody),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
* 将返回的内容中的所有识别出的文字信息进行组合
|
|
|
|
|
* @return 识别出的信息的内容字符串
|
|
|
|
|
*/
|
|
|
|
|
func decodeBody2Str(mbody map[string]interface{}) (str string) {
|
|
|
|
|
words, ok := mbody["words_result"]
|
|
|
|
|
if ok {
|
|
|
|
|
sliceWords, ok := words.([]interface{})
|
|
|
|
|
if ok {
|
|
|
|
|
// 遍历切片
|
|
|
|
|
for _, word := range sliceWords {
|
|
|
|
|
str += word.(map[string]interface{})["words"].(string) + "\n"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return str
|
|
|
|
|
}
|
|
|
|
|
return ""
|
|
|
|
|
}
|