Files
lone-services/services/analysis/internal/face/insightface.go
T
2026-11-02 10:06:20 +08:00

66 lines
1.7 KiB
Go

package face
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"lone-services/pkg/utils"
)
const faceEmbeddingDim = 512
type insightFaceResp struct {
Embedding []float32 `json:"embedding"`
Error string `json:"error"`
}
func GetFaceVector(imagePath string) ([]float32, error) {
host := utils.GetConfigString("services.skin_py_face_host")
apiPath := utils.GetConfigString("services.skin_py_face_path")
if host == utils.StringEmpty || apiPath == utils.StringEmpty {
return nil, fmt.Errorf("insightface config empty")
}
url := strings.TrimRight(host, "/") + apiPath
body, err := json.Marshal(map[string]string{"path": imagePath})
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
var errResp insightFaceResp
_ = json.Unmarshal(respBody, &errResp)
return nil, fmt.Errorf("face extraction failed (status %d): %s", resp.StatusCode, errResp.Error)
}
var result insightFaceResp
if err = json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("parse response: %w", err)
}
if len(result.Embedding) != faceEmbeddingDim {
return nil, fmt.Errorf("invalid embedding dimension: %d", len(result.Embedding))
}
return result.Embedding, nil
}