Files
sundynix-plant-be/service/plant/ocr.go
T
2026-02-10 12:35:46 +08:00

79 lines
2.5 KiB
Go

package plant
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"strings"
"sundynix-go/global"
"sundynix-go/model/plant/response"
"sundynix-go/pkg/httpclient"
"go.uber.org/zap"
)
type OcrService struct{}
// ClassifyPlant 植物识别
func (s *OcrService) ClassifyPlant(file multipart.File, header *multipart.FileHeader) (response.PlantRecognitionResponse, error) {
reqUrl := "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=" + getAccessToken()
// 3. 读取文件的全部字节
fileBytes, err := io.ReadAll(file)
if err != nil {
global.Logger.Error("读取文件失败!", zap.Error(err))
}
// 4. 将字节流编码为 Base64 字符串(可选 URLEncoding,根据场景选择)
// 去掉编码头进行urlencode
base64Str := base64.StdEncoding.EncodeToString(fileBytes)
escapedBase64 := url.QueryEscape(base64Str)
payload := strings.NewReader("image=" + escapedBase64 + "&baike_num=1")
myHttpClient := httpclient.GetClient()
req, err := http.NewRequest("POST", reqUrl, payload)
if err != nil {
global.Logger.Error("创建请求失败!", zap.Error(err))
return response.PlantRecognitionResponse{}, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Accept", "application/json")
resp, err := myHttpClient.Do(req)
if err != nil {
global.Logger.Error("请求百度接口失败!", zap.Error(err))
return response.PlantRecognitionResponse{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
global.Logger.Error("解析百度接口响应失败!", zap.Error(err))
return response.PlantRecognitionResponse{}, err
}
// 3. 解析JSON到结构体
var plantResp response.PlantRecognitionResponse
if err = json.Unmarshal(body, &plantResp); err != nil {
global.Logger.Error("解析识别JSON失败!", zap.Error(err))
}
return plantResp, err
}
func getAccessToken() string {
rpcUrl := "https://aip.baidubce.com/oauth/2.0/token"
postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", global.Config.BaiduImgClassify.ApiKey, global.Config.BaiduImgClassify.SecretKey)
resp, err := http.Post(rpcUrl, "application/x-www-form-urlencoded", strings.NewReader(postData))
if err != nil {
fmt.Println(err)
return ""
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return ""
}
accessTokenObj := map[string]any{}
_ = json.Unmarshal([]byte(body), &accessTokenObj)
return accessTokenObj["access_token"].(string)
}