feat: 植物识别记录

This commit is contained in:
Blizzard
2026-02-10 17:14:49 +08:00
parent 01f8306be2
commit dd6a638982
6 changed files with 163 additions and 16 deletions
+57 -1
View File
@@ -10,6 +10,8 @@ import (
"net/url"
"strings"
"sundynix-go/global"
"sundynix-go/model/commom/request"
"sundynix-go/model/plant"
"sundynix-go/model/plant/response"
"sundynix-go/pkg/httpclient"
@@ -19,7 +21,7 @@ import (
type OcrService struct{}
// ClassifyPlant 植物识别
func (s *OcrService) ClassifyPlant(file multipart.File, header *multipart.FileHeader) (response.PlantRecognitionResponse, error) {
func (s *OcrService) ClassifyPlant(file multipart.File, header *multipart.FileHeader, userId string) (response.PlantRecognitionResponse, error) {
reqUrl := "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=" + getAccessToken()
// 3. 读取文件的全部字节
fileBytes, err := io.ReadAll(file)
@@ -55,7 +57,61 @@ func (s *OcrService) ClassifyPlant(file multipart.File, header *multipart.FileHe
if err = json.Unmarshal(body, &plantResp); err != nil {
global.Logger.Error("解析识别JSON失败!", zap.Error(err))
}
//4.异步写入库
go func(userId string, apiResp response.PlantRecognitionResponse) {
// A. 安全防护:防止协程 Panic 导致程序崩溃
defer func() {
if r := recover(); r != nil {
global.Logger.Error("异步入库发生 Panic", zap.Any("recover", r))
}
}()
var dbResults plant.ResultsArray = make(plant.ResultsArray, 0, len(apiResp.Result))
// 2. 循环搬运数据
for _, item := range apiResp.Result {
// 处理嵌套的 BaikeInfo 指针
var baikeInfo *plant.BaikeInfo
if item.BaikeInfo != nil {
baikeInfo = &plant.BaikeInfo{
BaikeUrl: item.BaikeInfo.BaikeUrl,
ImageUrl: item.BaikeInfo.ImageUrl,
Description: item.BaikeInfo.Description,
}
}
// 添加转换后的对象
dbResults = append(dbResults, plant.ResultItem{
Score: item.Score,
Name: item.Name,
BaikeInfo: baikeInfo, // 赋值刚才处理好的指针
})
}
record := plant.ClassifyRecord{
UserId: userId,
LogId: apiResp.LogId,
AllResults: dbResults,
}
if err := global.DB.Create(&record).Error; err != nil {
global.Logger.Error("异步植物识别结果入库失败", zap.Error(err))
}
}(userId, plantResp)
// 立即返回结果
return plantResp, err
}
// MyClassifyLog 我的植物识别记录
func (s *OcrService) MyClassifyLog(req request.PageInfo, id string) (list interface{}, total int64, err error) {
limit := req.PageSize
offset := req.PageSize * (req.Current - 1)
db := global.DB.Model(&plant.ClassifyRecord{})
var records []plant.ClassifyRecord
err = db.Count(&total).Error
if err != nil {
return
}
db = db.Where("user_id = ?", id).Limit(limit).Offset(offset).Order("created_at desc").Find(&records)
return records, total, err
}
func getAccessToken() string {