mirror of
https://github.com/mudler/LocalAI.git
synced 2026-07-10 00:08:42 -04:00
* feat(voice-detect): add Go purego backend for voice-detect.cpp Add backend/go/voice-detect implementing the Backend gRPC voice subset (VoiceEmbed/VoiceVerify/VoiceAnalyze) over libvoicedetect.so via purego, mirroring the parakeet-cpp / omnivoice-cpp backends. The flat voicedetect_capi C ABI is dlopen'd cgo-less; malloc'd string and float-vector returns are owned by Go and released through the matching capi free functions, with the per-ctx last error surfaced into Go errors. Calls are serialized via base.SingleThread since the C context is not reentrant. Proto field mapping: - VoiceEmbed: VoiceEmbedRequest.audio (path) -> embed_path -> Embedding+Model. - VoiceVerify: audio1/audio2 + threshold (<=0 falls back to the verify_threshold option, default 0.25) -> verify_paths -> verified/distance/ threshold/confidence/model/processing_time_ms. - VoiceAnalyze: audio (path) -> analyze_path_json; the JSON age/gender/emotion document maps to a single VoiceAnalysis segment (start/end 0; gender "label" -> dominant_gender with the remaining float scores as the gender map; emotion label/scores -> dominant_emotion/emotion). The Makefile pins voice-detect.cpp to 47546430, clones+builds libvoicedetect.so with ggml static-linked (PIC, GGML_NATIVE off) so dlopen needs no external libggml/libvoicedetect; ldd on the artifact shows only system libs. Ginkgo tests cover option parsing and analyze-JSON mapping; embed/verify smoke specs gate on VOICEDETECT_BACKEND_TEST_MODEL + VOICEDETECT_BACKEND_TEST_WAV. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(voice-detect): wire backend into index, gallery and build Register the voice-detect.cpp speaker-recognition + voice-analysis backend (added in Voice-INT-A) into LocalAI's distribution surfaces, mirroring the ced backend (the closest mudler C++/ggml audio analogue): - backend/index.yaml: add the &voicedetect meta-backend (capabilities platform map, no top-level uri) plus the full set of concrete per-arch image entries (cpu/cuda12/cuda13/metal/rocm/sycl/vulkan/l4t and the -development variants). Referential integrity audited - every alias target resolves. - gallery/index.yaml: add 5 model entries on backend voice-detect - ECAPA-TDNN, WeSpeaker ResNet34, 3D-Speaker ERes2Net, CAM++ and the wav2vec2 age/gender/emotion analyze model. The engine architecture is read from GGUF metadata (voicedetect.arch) at load. GGUF artifacts are not yet published: each files: entry points at the intended mudler/voice-detect-gguf location with a TODO to fill sha256 after upload (no fabricated hashes). - .github/backend-matrix.yml: add the linux build matrix block + the darwin metal entry mirroring ced. - .github/workflows/bump_deps.yaml: track mudler/voice-detect.cpp via VOICEDETECT_VERSION (pin 47546430, = 4754643). - core/config/backend_capabilities.go: register voice-detect in the backend capability map (VoiceVerify/VoiceEmbed/VoiceAnalyze -> speaker_recognition), mirroring speaker-recognition. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(face-detect): add purego Go backend for face-detect.cpp Add the LocalAI Go backend that dlopens libfacedetect.so (the flat facedetect_capi_* C-ABI) via purego, mirroring the sibling voice-detect backend. Implements the Face subset of the Backend gRPC service: - Embeddings(PredictOptions): Images[0] base64 -> temp file -> embed_path -> L2-normalized ArcFace embedding. - Detect(DetectOptions): src -> detect_path_json -> Detection boxes (class_name "face", [x1,y1,x2,y2] -> x/y/w/h). - FaceVerify(FaceVerifyRequest): two images + threshold + anti_spoof -> verify_paths; best-effort img areas via detect. - FaceAnalyze(FaceAnalyzeRequest): img -> analyze_path_json -> per-face age + gender ("M"/"F" normalized to "Man"/"Woman"). The Makefile pins face-detect.cpp to 636a1963 and builds the shared lib with ggml + vendored libjpeg-turbo static (PIC), so the .so is ldd-clean (no libggml) and exports only facedetect_capi_* (no jpeg_ symbols). Gated Ginkgo e2e mirrors voice-detect. Note for the gallery-wiring task: backend registration (index.yaml, gallery, core/config/backend_capabilities.go) is intentionally not touched here. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * fix(voice-detect): replace em dashes in net-new descriptions Project style forbids em/en dashes. Replace the three U+2014 chars introduced by the voice-detect gallery/index wiring with `-`/`:`. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(face-detect): wire backend into index, gallery and build Register the face-detect.cpp face detection / embedding / verification / analysis backend (added in Face-INT-A) into LocalAI's distribution surfaces, mirroring the voice-detect wiring (the closest mudler C++/ggml recognition analogue): - backend/index.yaml: add the &facedetect meta-backend (capabilities platform map, no top-level uri to avoid the meta-backend gotcha) plus the full set of concrete per-arch image entries (cpu/cuda12/cuda13/ metal/rocm/sycl-f16/sycl-f32/vulkan/l4t and the -development variants), 22 entries. Referential integrity audited: every alias target resolves. - gallery/index.yaml: add 4 model entries on backend face-detect - face-detect-buffalo-l/m/s (insightface SCRFD + ArcFace/MBF, NON-COMMERCIAL) and face-detect-yunet-sface (OpenCV-Zoo YuNet + SFace, APACHE-2.0, the commercial-friendly alternative). The detector/embedder architecture is read from GGUF metadata (facedetect.arch) at load; only the real verify_threshold option is set (0.35 buffalo, 0.363 sface). GGUF artifacts are not yet published: each files: entry points at the intended mudler/face-detect-gguf location with a TODO to fill sha256 after upload (no fabricated hashes). - core/config/backend_capabilities.go: register face-detect in the backend capability map (Embedding/Detect/FaceVerify/FaceAnalyze -> face_recognition), mirroring insightface. - .github/backend-matrix.yml: add the linux build matrix block + the darwin metal entry mirroring voice-detect. - .github/workflows/bump_deps.yaml: track mudler/face-detect.cpp via FACEDETECT_VERSION (pin 636a1963). Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * fix(recon): voice-detect metal build branch + face-detect gallery usecases Add the missing metal BUILD_TYPE branch to the voice-detect Makefile forwarding -DVOICEDETECT_GGML_METAL=ON, mirroring face-detect, so the darwin metal CI artifact is built with the Metal backend instead of CPU-only. Expand the 4 face-detect gallery models' known_usecases to [face_recognition, detection, embeddings] to match the backend capabilities map and the mirrored insightface-buffalo entries, so auto-selection for /v1/detect and /embeddings works. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * docs(recon): document voice-detect and face-detect ggml backends Document the new standalone C++/ggml biometric backends as the recommended/default option for face and voice recognition, keeping the existing Python insightface / speaker-recognition backends framed as the legacy path. - features/face-recognition.md: add a face-detect (ggml) backend section with the gallery entries (buffalo-l/m/s non-commercial, yunet-sface Apache-2.0), licensing, and verify/detect/analyze quickstart. - features/voice-recognition.md: add a voice-detect (ggml) backend section with the gallery entries (ecapa-tdnn, wespeaker-resnet34, eres2net, campplus speaker recognizers; emotion-wav2vec2 non-commercial analyze head) and quickstart. - reference/compatibility-table.md: add face-detect.cpp and voice-detect.cpp rows to the Vision, Detection & Recognition table. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(gallery): publish recon backend GGUF uris + sha256 Fill in the published HuggingFace GGUF uris and verified sha256 for the 9 recon gallery entries (voice-detect-* and face-detect-*), and remove the TODO publish markers. Correct the eres2net, campplus, and emotion-wav2vec2 uris to the actual published filenames. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(gallery): re-embed buffalo anti-spoof + add audeering age/gender voice model Update the 3 buffalo face-detect GGUF sha256 (anti-spoof ensemble now embedded and re-uploaded under the same filenames/uris) and note the FaceVerify anti_spoof request flag in each description. Add a new voice-detect-age-gender-wav2vec2 gallery entry mirroring the emotion model. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(gallery): add face-detect-buffalo-sc and antelopev2 packs Add gallery entries for two newly-published insightface face packs on the face-detect backend: buffalo_sc (smallest pack, SCRFD-500M + small ArcFace) and antelopev2 (higher-accuracy, SCRFD-10G + ArcFace glint360k R100, 512-d). Both are non-commercial research-only. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(recon): honor LocalAI per-model threads in voice/face-detect backends LocalAI spawns one backend process per model and serves requests concurrently, so the engines' own min(hardware_concurrency, 8) default can oversubscribe cores. Forward the per-model Threads value from the gRPC LoadModel options into the engine via VOICEDETECT_THREADS / FACEDETECT_THREADS (read at backend construction) before the capi load. A non-positive Threads is treated as unset, leaving the engine default. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump backend pins to CPU-optimized engine commits voice-detect.cpp -> 0d9c1b3 (radix-2 FFT FBank, threads, flash attn + cached pos-conv); face-detect.cpp -> 523aee1 (thread-gated direct conv, threads). Brings the CPU optimizations into the LocalAI backend builds. GGUF format and parity unchanged, so the published HF GGUFs remain valid. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump backend pins to round-2 CPU-optimized engines voice-detect.cpp -> fe7e6a3 (ERes2Net 1x1->mul_mat, CAM++ layout+context, wav2vec2 conv-LN, ECAPA capture-drop, AVX512 dispatch opt-in); face-detect.cpp -> 9c8adb7 (AVX2 Winograd F(2x2,3x3) for SCRFD/ArcFace 3x3 convs, ArcFace BN-fold). Parity unchanged (cosine=1.0); GGUF format unchanged, HF GGUFs valid. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump backend pins to round-3 Winograd engines voice-detect.cpp -> 45122ec (Winograd F(2x2,3x3) for WeSpeaker/ERes2Net 3x3 convs, -22%/-20% @8t); face-detect.cpp -> cd5c962 (Winograd F(4x4,3x3) for SCRFD large maps, -22% @1t on top of F(2x2), more load-stable). Parity held (cosine=1.0); GGUF format unchanged, HF GGUFs valid. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump backend pins to round-4 Winograd engines (CPU opt complete) voice-detect.cpp -> d2839ca (CAM++ FCM 2D convs through Winograd, -15.5%/-10.3%); face-detect.cpp -> c1db23d (AVX2-vectorized Winograd tile transforms, SCRFD detect -14%/-9.6%). Final CPU optimization round; the conv-kernel lever class is now exhausted (parity held cosine=1.0; GGUF/parity unchanged, HF GGUFs valid). Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump face-detect pin to deep-kernel engine (7ae5c4d) face-detect.cpp -> 7ae5c4d: register-blocked winograd-domain GEMM microkernel (2.8x isolated GFLOP/s), AVX-512 zmm evolution behind runtime CPUID dispatch (ship-safe, AVX2 fallback bit-identical), bias/relu fused into the winograd output transform, and SFace Conv+BN fold + bias/PReLU fusion. SCRFD detect ~1.4x faster end-to-end vs the round-4 baseline; parity bit-exact; portable single binary (function-multiversioned, no global -mavx512f). Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump voice-detect pin to ECAPA operand-order win (e9c56ae) voice-detect.cpp -> e9c56ae: weight-as-src0 mul_mat order in ECAPA's F32 conv1d_same (routes through tinyBLAS sgemm); ECAPA embed 1.67x @1t / ~1.3x @8t, parity cosine=1.0. Isolated to encoder.cpp (ECAPA-only); ERes2Net/CAM++/WeSpeaker do not call conv1d_same so are provably unaffected. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump pins to FMA-throughput engines (voice f7b9f89, face 2d2d5f0) face -> 2d2d5f0: route ArcFace 3x3 body convs through the AVX-512 winograd microkernel (kWinoMinSize 80->14); ArcFace 1.62x @1t, SCRFD detect to 0.966 of MLAS @1t, no regression. voice -> f7b9f89: runtime-CPUID-dispatched AVX-512 winograd-GEMM microkernel (ship-safe, AVX2 fallback bit-identical); WeSpeaker 1.90x @1t. Parity cosine=1.0 throughout; portable single binaries. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump pins to MLAS-class direct-conv engines (voice 7ecfd07, face be22d67) Hand-tuned nChw16c AVX-512 register-tiled direct-conv microkernel (~263 GFLOP/s, within 6-7% of MLAS per-op efficiency), runtime-CPUID-dispatched + AVX2 fallback, fused bias/relu. voice 7ecfd07: default 3x3-s1 kernel for WeSpeaker (+37%/+32%) + ERes2Net, CAM++ pinned to Winograd. face be22d67: shape-gated to the ArcFace recognizer body (+25-27% @8t); SCRFD detector stays on Winograd (no regression). Parity cosine=1.0 / detect <=1px on AVX-512 + AVX2 paths. Portable single binaries. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump voice pin to Phase-A blocked backbone (f4e7eef) WeSpeaker ResNet34 runs as one nChw16c blocked island (2 reorders/forward vs ~60) on AVX-512, default; per-conv directconv fallback on AVX2. +2.9% @1t / +17-19% @8t vs per-conv directconv, parity cosine=1.0. The conv microkernel is already FMA-bound near peak (~0.86-0.98x MLAS-implied); residual to MLAS is sub-peak edge + non-conv tail, documented in docs/cpu-optimization.md. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump pins to breadth blocked-backbone (voice 7f66871, face d80092b) voice 7f66871: AVX2-vectorized (ymm) blocked island - AVX2-only hosts now run the blocked backbone for WeSpeaker (2.3x over per-conv-AVX2, cosine=1.0); ERes2Net stays per-conv (blocked regresses, opt-in only); CAM++ Winograd-pinned. face d80092b: ArcFace recognizer blocked island, AVX-512 default (-13% @8t, ~0.90x MLAS, the closest conv result), auto per-conv on AVX2; SCRFD untouched on Winograd (0 island invocations during detect). Parity cosine=1.0 / detect <=1px throughout. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump pins to small-spatial + stem conv kernels (voice 99b1804, face 47fdab6) Measured-gap-driven conv kernels: small-spatial (fill the register tile when output width <= tile width) + small-IC stem + strided-1x1/downsample recovery. ArcFace recognizer 0.57 -> 0.70x MLAS @1t (the closest conv model), WeSpeaker 0.65 -> 0.79x @1t. Parity cosine=1.0 / detect <=1px. The OC-block-sharing lever was a measured dead-end (deep stride-1 is L3-weight-bandwidth bound, not read-port bound) and was NOT shipped. Kernel ceiling reached; further gap needs an algorithm-class change (cache-blocked weight-stationary GEMM, or q8 weights). Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump pins to GPU persistent-graph + multi-model-safe cache (voice 45d2e6b, face 0a4799a) GPU wins (CUDA/ggml backend, no CPU-path change): persistent per-shape graph+context cache in Backend::compute() eliminates the per-call cudaGraph re-instantiation churn -> wav2vec2 emotion+age-gender now AT GPU parity with torch-cuDNN on GB10 (0.97-0.98x), CAM++ -5.7ms; bit-identical parity. Cache hardened multi-model-safe (invalidate-on-free keyed by the ModelLoader weights buffer) so LocalAI multi-model hosting cannot stale-hit. Conv models still trail cuDNN (im2col-materialization-bound) - cuDNN implicit-GEMM lever next. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump pins to cuDNN-conv-capable engines (voice b6e4356, face 6107a24) Adds the opt-in cuDNN implicit-GEMM conv path (VOICEDETECT_GGML_CUDNN / FACEDETECT_GGML_CUDNN, DEFAULT OFF -> zero build/runtime dep until enabled). On GPU it kills the im2col-materialization bottleneck and reaches torch-cuDNN parity on the spill-bound convs: SCRFD detect 14.8->6.4ms (2.3x, ~parity), WeSpeaker ~parity, ERes2Net beats torch (1.10x); ArcFace/CAM++ neutral (no spill). Parity exact (SCRFD <=1px, cosine=1.0). To USE it in LocalAI, the CUDA backend build must enable the flag AND bundle libcudnn - deferred until a cuDNN-bundled GPU image; flag stays OFF here. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * feat(recon): enable cuDNN conv path on arm64+CUDA13 recon backends The voice-detect.cpp / face-detect.cpp engines have an opt-in cuDNN implicit-GEMM conv path behind VOICEDETECT_GGML_CUDNN / FACEDETECT_GGML_CUDNN (default OFF) that kills im2col on the GPU and reaches torch-cuDNN parity (SCRFD 2.3x, WeSpeaker/ERes2Net parity), measured on the GB10 (arm64, CUDA 13, sm_121a). Enable it for the CUDA build, but only where cuDNN actually ships: the arm64 + CUDA 13 image (GB10/Jetson/L4T). x86 CUDA images carry no cuDNN, so flipping it on globally for BUILD_TYPE=cublas would be a link failure. The Makefiles gate on CUDA_MAJOR_VERSION=13 + arch (TARGETARCH from the matrix/Docker build, uname -m fallback for local builds). backend/Dockerfile.golang already installs the runtime libcudnn9-cuda-13 in the arm64+CUDA13 apt block; add the matching libcudnn9-dev-cuda-13 so the build-time link resolves. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): bump voice-detect pin to ERes2Net blocked-default (30beecd) Defaults VD_ERES2NET_BLOCKED ON: routes the ERes2Net Res2Net body through the blocked nChw16c AVX-512 directconv island instead of the 1x1 mul_mat fast path (CONT-transpose + skinny low-K GEMM). On the shipped GGML_NATIVE=OFF build (ggml mul_mat is AVX2-only) this wins ~2x at every thread count (2.07x@1t, 2.2x@4t, 2.05x@8t); pure-AVX2 fallback still 1.3-1.62x. Parity exact (cosine=1.000000 vs golden), so registered voices + verify/identify thresholds are unaffected. The prior default-OFF rested on a stale comment whose 23pct regression only held on the non-shipping GGML_NATIVE=ON build. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * docs(readme): announce native voice-detect + face-detect backends in Latest News Add a Latest News entry for the new from-scratch C++/ggml biometric backends (voice-detect.cpp + face-detect.cpp) that replace the Python insightface and speaker-recognition backends: no Python/onnxruntime at inference, self-contained GGUF, bit-exact parity, GPU cuDNN parity. Mirrors the parakeet.cpp / locate-anything.cpp native-backend news entries. Refs PR #10441. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] * chore(recon): re-pin to the squashed engine release commits The voice-detect.cpp and face-detect.cpp histories were squashed to a single release commit, which orphaned the previous pins (voice 30beecd, face 6107a24). Re-pin to the new single-commit SHAs (voice 3d51077, face 06914b0); the tree is identical, so the backend build is unchanged. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-4-8 [Claude Code] --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
432 lines
14 KiB
Go
432 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unsafe"
|
|
|
|
"github.com/mudler/LocalAI/pkg/grpc/base"
|
|
pb "github.com/mudler/LocalAI/pkg/grpc/proto"
|
|
"github.com/mudler/xlog"
|
|
)
|
|
|
|
// purego-bound entry points from libfacedetect.so. Names match
|
|
// facedetect_capi.h exactly so a `nm libfacedetect.so | grep facedetect_capi`
|
|
// is enough to spot drift.
|
|
//
|
|
// The opaque ctx and the malloc'd char*/float* return values are declared as
|
|
// uintptr so we get the raw pointer back and can release it via the matching
|
|
// capi free function. purego's native string/[]float32 returns would copy and
|
|
// forget the original pointer, leaking the C-owned buffer on every call.
|
|
var (
|
|
CppAbiVersion func() int32
|
|
CppLoad func(ggufPath string) uintptr
|
|
CppFree func(ctx uintptr)
|
|
CppLastError func(ctx uintptr) string
|
|
CppFreeString func(s uintptr)
|
|
CppFreeVec func(v uintptr)
|
|
CppEmbedPath func(ctx uintptr, imagePath string, outVec, outDim unsafe.Pointer) int32
|
|
CppEmbedRGB func(ctx uintptr, rgb []byte, width, height int32, outVec, outDim unsafe.Pointer) int32
|
|
CppDetectJSON func(ctx uintptr, imagePath string) uintptr
|
|
CppVerifyPaths func(ctx uintptr, a, b string, threshold float32, antiSpoof int32, outDistance, outVerified unsafe.Pointer) int32
|
|
CppAnalyzeJSON func(ctx uintptr, imagePath string) uintptr
|
|
)
|
|
|
|
// FaceDetect implements the face-recognition (biometric) subset of the Backend
|
|
// gRPC service over libfacedetect.so. The C side keeps a single loaded model
|
|
// pack plus a per-ctx last-error buffer and is not reentrant, so
|
|
// base.SingleThread serializes every call.
|
|
type FaceDetect struct {
|
|
base.SingleThread
|
|
opts loadOptions
|
|
ctxPtr uintptr
|
|
}
|
|
|
|
func (f *FaceDetect) Load(opts *pb.ModelOptions) error {
|
|
model := opts.ModelFile
|
|
if model == "" {
|
|
model = opts.ModelPath
|
|
}
|
|
if !filepath.IsAbs(model) && opts.ModelPath != "" {
|
|
model = filepath.Join(opts.ModelPath, model)
|
|
}
|
|
if model == "" {
|
|
return errors.New("face-detect: ModelFile is required")
|
|
}
|
|
|
|
f.opts = parseOptions(opts.Options)
|
|
if f.opts.modelName == "" {
|
|
f.opts.modelName = filepath.Base(model)
|
|
}
|
|
|
|
// Propagate LocalAI's per-model thread budget to the engine. LocalAI spawns
|
|
// one backend process per model and serves requests concurrently, so the
|
|
// engine's own min(hardware_concurrency, 8) default can oversubscribe cores.
|
|
// FACEDETECT_THREADS is read by the engine at backend construction, so it
|
|
// must be set before the capi load. A non-positive Threads means "unset":
|
|
// leave the env alone so the engine keeps its sane default.
|
|
threads := opts.Threads
|
|
if threads > 0 {
|
|
if err := os.Setenv("FACEDETECT_THREADS", strconv.Itoa(int(threads))); err != nil {
|
|
return fmt.Errorf("face-detect: set FACEDETECT_THREADS: %w", err)
|
|
}
|
|
xlog.Info("face-detect: applying LocalAI thread budget", "threads", threads)
|
|
}
|
|
|
|
xlog.Info("face-detect: loading model", "model", model,
|
|
"verify_threshold", f.opts.verifyThreshold, "abi", CppAbiVersion())
|
|
|
|
ctx := CppLoad(model)
|
|
if ctx == 0 {
|
|
// The last-error buffer lives on the ctx that was never returned, so
|
|
// surface the path the operator tried to load instead.
|
|
return fmt.Errorf("face-detect: facedetect_capi_load failed for %q", model)
|
|
}
|
|
f.ctxPtr = ctx
|
|
return nil
|
|
}
|
|
|
|
// Embeddings returns the L2-normalized ArcFace embedding of the primary face in
|
|
// the supplied image. Mirroring the Python face backend, the image is read from
|
|
// Images[0] as a base64 payload; materializeImage decodes it to a temp file so
|
|
// the path-based C-API can run its own decode (cv2.imread parity). The gRPC
|
|
// server wraps the returned slice in an EmbeddingResult.
|
|
func (f *FaceDetect) Embeddings(req *pb.PredictOptions) ([]float32, error) {
|
|
if f.ctxPtr == 0 {
|
|
return nil, errors.New("face-detect: model not loaded")
|
|
}
|
|
if len(req.Images) == 0 || req.Images[0] == "" {
|
|
return nil, errors.New("face-detect: Embedding requires Images[0] to be a base64 image")
|
|
}
|
|
|
|
path, cleanup, err := materializeImage(req.Images[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cleanup()
|
|
|
|
return f.embedPath(path)
|
|
}
|
|
|
|
func (f *FaceDetect) embedPath(path string) ([]float32, error) {
|
|
var vec uintptr
|
|
var dim int32
|
|
rc := CppEmbedPath(f.ctxPtr, path, unsafe.Pointer(&vec), unsafe.Pointer(&dim))
|
|
if rc != 0 || vec == 0 || dim <= 0 {
|
|
return nil, f.lastErr("embed", path)
|
|
}
|
|
defer CppFreeVec(vec)
|
|
// Copy out of the C-owned malloc'd buffer before freeing it. The
|
|
// uintptr->Pointer conversion trips vet's unsafeptr check, which can't tell
|
|
// a C heap pointer from Go-managed memory; safe here, the GC neither tracks
|
|
// nor moves this buffer and we copy immediately.
|
|
src := unsafe.Slice((*float32)(unsafe.Pointer(vec)), int(dim)) //nolint:govet // C-owned malloc'd vector, copied out before free
|
|
out := make([]float32, int(dim))
|
|
copy(out, src)
|
|
return out, nil
|
|
}
|
|
|
|
// Detect runs SCRFD over the image and returns one Detection per face. The
|
|
// C-API emits a box as [x1,y1,x2,y2] in pixels; the proto carries x/y plus
|
|
// width/height, so the corners are converted. The 5 facial landmarks the engine
|
|
// also returns are dropped: the Detection message has no field for them.
|
|
func (f *FaceDetect) Detect(req *pb.DetectOptions) (pb.DetectResponse, error) {
|
|
if f.ctxPtr == 0 {
|
|
return pb.DetectResponse{}, errors.New("face-detect: model not loaded")
|
|
}
|
|
if req.Src == "" {
|
|
return pb.DetectResponse{}, errors.New("face-detect: src image is required")
|
|
}
|
|
|
|
path, cleanup, err := materializeImage(req.Src)
|
|
if err != nil {
|
|
return pb.DetectResponse{}, err
|
|
}
|
|
defer cleanup()
|
|
|
|
faces, err := f.detectFaces(path)
|
|
if err != nil {
|
|
return pb.DetectResponse{}, err
|
|
}
|
|
|
|
dets := make([]*pb.Detection, 0, len(faces))
|
|
for _, fc := range faces {
|
|
if req.Threshold > 0 && fc.Score < req.Threshold {
|
|
continue
|
|
}
|
|
x, y, w, h := fc.xywh()
|
|
dets = append(dets, &pb.Detection{
|
|
X: x,
|
|
Y: y,
|
|
Width: w,
|
|
Height: h,
|
|
Confidence: fc.Score,
|
|
ClassName: "face",
|
|
})
|
|
}
|
|
return pb.DetectResponse{Detections: dets}, nil
|
|
}
|
|
|
|
// FaceVerify embeds the primary face in each image and reports whether they are
|
|
// the same identity by cosine distance against a threshold. A request threshold
|
|
// <= 0 falls back to the model-configured default (verify_threshold option,
|
|
// 0.35 if unset). When anti_spoofing is set, the C-API applies a MiniFASNet
|
|
// veto internally (verified forced false on a spoof); the per-image liveness
|
|
// scores are not exposed by the verify entry point, so img*_is_real /
|
|
// img*_antispoof_score stay at their zero values.
|
|
func (f *FaceDetect) FaceVerify(req *pb.FaceVerifyRequest) (pb.FaceVerifyResponse, error) {
|
|
if f.ctxPtr == 0 {
|
|
return pb.FaceVerifyResponse{}, errors.New("face-detect: model not loaded")
|
|
}
|
|
if req.Img1 == "" || req.Img2 == "" {
|
|
return pb.FaceVerifyResponse{}, errors.New("face-detect: img1 and img2 are required")
|
|
}
|
|
|
|
path1, cleanup1, err := materializeImage(req.Img1)
|
|
if err != nil {
|
|
return pb.FaceVerifyResponse{}, err
|
|
}
|
|
defer cleanup1()
|
|
path2, cleanup2, err := materializeImage(req.Img2)
|
|
if err != nil {
|
|
return pb.FaceVerifyResponse{}, err
|
|
}
|
|
defer cleanup2()
|
|
|
|
threshold := req.Threshold
|
|
if threshold <= 0 {
|
|
threshold = f.opts.verifyThreshold
|
|
}
|
|
|
|
antiSpoof := int32(0)
|
|
if req.AntiSpoofing {
|
|
antiSpoof = 1
|
|
}
|
|
|
|
started := time.Now()
|
|
var distance float32
|
|
var verified int32
|
|
rc := CppVerifyPaths(f.ctxPtr, path1, path2, threshold, antiSpoof,
|
|
unsafe.Pointer(&distance), unsafe.Pointer(&verified))
|
|
if rc != 0 {
|
|
return pb.FaceVerifyResponse{}, f.lastErr("verify", req.Img1[:min(8, len(req.Img1))]+"...")
|
|
}
|
|
elapsedMs := float32(time.Since(started).Seconds() * 1000.0)
|
|
|
|
// Confidence decays linearly from 100 at distance 0 to 0 at the threshold,
|
|
// matching the Python face backend's reporting.
|
|
confidence := float32(0)
|
|
if threshold > 0 {
|
|
confidence = float32(math.Max(0, math.Min(100, (1.0-float64(distance)/float64(threshold))*100.0)))
|
|
}
|
|
|
|
return pb.FaceVerifyResponse{
|
|
Verified: verified != 0,
|
|
Distance: distance,
|
|
Threshold: threshold,
|
|
Confidence: confidence,
|
|
Model: f.opts.modelName,
|
|
Img1Area: f.bestArea(path1),
|
|
Img2Area: f.bestArea(path2),
|
|
ProcessingTimeMs: elapsedMs,
|
|
}, nil
|
|
}
|
|
|
|
// FaceAnalyze runs the genderage head on every detected face. The C-API returns
|
|
// "M"/"F" gender labels and a rounded age; the labels are normalized to the
|
|
// "Man"/"Woman" values the proto documents.
|
|
func (f *FaceDetect) FaceAnalyze(req *pb.FaceAnalyzeRequest) (pb.FaceAnalyzeResponse, error) {
|
|
if f.ctxPtr == 0 {
|
|
return pb.FaceAnalyzeResponse{}, errors.New("face-detect: model not loaded")
|
|
}
|
|
if req.Img == "" {
|
|
return pb.FaceAnalyzeResponse{}, errors.New("face-detect: img is required")
|
|
}
|
|
|
|
path, cleanup, err := materializeImage(req.Img)
|
|
if err != nil {
|
|
return pb.FaceAnalyzeResponse{}, err
|
|
}
|
|
defer cleanup()
|
|
|
|
ptr := CppAnalyzeJSON(f.ctxPtr, path)
|
|
if ptr == 0 {
|
|
return pb.FaceAnalyzeResponse{}, f.lastErr("analyze", path)
|
|
}
|
|
defer CppFreeString(ptr)
|
|
|
|
faces, err := parseAnalyzeJSON(goStringFromCPtr(ptr))
|
|
if err != nil {
|
|
return pb.FaceAnalyzeResponse{}, fmt.Errorf("face-detect: analyze JSON: %w", err)
|
|
}
|
|
return pb.FaceAnalyzeResponse{Faces: faces}, nil
|
|
}
|
|
|
|
// faceBox is one entry of the detect/analyze JSON documents the engine emits.
|
|
type faceBox struct {
|
|
Score float32 `json:"score"`
|
|
Box []float32 `json:"box"`
|
|
Age float32 `json:"age"`
|
|
Gender string `json:"gender"`
|
|
}
|
|
|
|
// xywh converts the engine's [x1,y1,x2,y2] box into the x/y/width/height the
|
|
// proto carries. A short or missing box yields zeros.
|
|
func (b faceBox) xywh() (x, y, w, h float32) {
|
|
if len(b.Box) < 4 {
|
|
return 0, 0, 0, 0
|
|
}
|
|
return b.Box[0], b.Box[1], b.Box[2] - b.Box[0], b.Box[3] - b.Box[1]
|
|
}
|
|
|
|
type facesJSON struct {
|
|
Faces []faceBox `json:"faces"`
|
|
}
|
|
|
|
func (f *FaceDetect) detectFaces(path string) ([]faceBox, error) {
|
|
ptr := CppDetectJSON(f.ctxPtr, path)
|
|
if ptr == 0 {
|
|
return nil, f.lastErr("detect", path)
|
|
}
|
|
defer CppFreeString(ptr)
|
|
|
|
var doc facesJSON
|
|
if err := json.Unmarshal([]byte(goStringFromCPtr(ptr)), &doc); err != nil {
|
|
return nil, fmt.Errorf("face-detect: detect JSON: %w", err)
|
|
}
|
|
return doc.Faces, nil
|
|
}
|
|
|
|
// bestArea returns the FacialArea of the highest-scoring face in an image, or an
|
|
// empty area when detection fails or finds nothing. Best-effort: verify already
|
|
// succeeded, so a missing region must not turn a valid match into an error.
|
|
func (f *FaceDetect) bestArea(path string) *pb.FacialArea {
|
|
faces, err := f.detectFaces(path)
|
|
if err != nil || len(faces) == 0 {
|
|
return &pb.FacialArea{}
|
|
}
|
|
best := faces[0]
|
|
for _, fc := range faces[1:] {
|
|
if fc.Score > best.Score {
|
|
best = fc
|
|
}
|
|
}
|
|
x, y, w, h := best.xywh()
|
|
return &pb.FacialArea{X: x, Y: y, W: w, H: h}
|
|
}
|
|
|
|
// parseAnalyzeJSON maps the engine's analyze document onto FaceAnalysis entries.
|
|
// The engine reports gender as "M"/"F"; both the dominant label and the score
|
|
// map are filled with the "Man"/"Woman" form the proto documents.
|
|
func parseAnalyzeJSON(doc string) ([]*pb.FaceAnalysis, error) {
|
|
var parsed facesJSON
|
|
if err := json.Unmarshal([]byte(doc), &parsed); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
out := make([]*pb.FaceAnalysis, 0, len(parsed.Faces))
|
|
for _, fc := range parsed.Faces {
|
|
x, y, w, h := fc.xywh()
|
|
fa := &pb.FaceAnalysis{
|
|
Region: &pb.FacialArea{X: x, Y: y, W: w, H: h},
|
|
FaceConfidence: fc.Score,
|
|
Age: fc.Age,
|
|
}
|
|
if label := normalizeGender(fc.Gender); label != "" {
|
|
fa.DominantGender = label
|
|
fa.Gender = map[string]float32{label: 1.0}
|
|
}
|
|
out = append(out, fa)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// normalizeGender maps the engine's "M"/"F" code to the "Man"/"Woman" labels the
|
|
// proto documents. Unknown codes pass through unchanged.
|
|
func normalizeGender(g string) string {
|
|
switch strings.ToUpper(strings.TrimSpace(g)) {
|
|
case "M":
|
|
return "Man"
|
|
case "F":
|
|
return "Woman"
|
|
case "":
|
|
return ""
|
|
default:
|
|
return g
|
|
}
|
|
}
|
|
|
|
// materializeImage decodes a base64 image payload into a temp file and returns
|
|
// its path plus a cleanup func. As a convenience for callers that already pass a
|
|
// filesystem path (e.g. a test fixture), an existing path is used as-is with a
|
|
// no-op cleanup. data: URI prefixes are stripped before decoding.
|
|
func materializeImage(src string) (path string, cleanup func(), err error) {
|
|
noop := func() {}
|
|
if src == "" {
|
|
return "", noop, errors.New("face-detect: empty image input")
|
|
}
|
|
if _, statErr := os.Stat(src); statErr == nil {
|
|
return src, noop, nil
|
|
}
|
|
|
|
payload := src
|
|
if i := strings.Index(payload, ","); strings.HasPrefix(payload, "data:") && i >= 0 {
|
|
payload = payload[i+1:]
|
|
}
|
|
data, decErr := base64.StdEncoding.DecodeString(strings.TrimSpace(payload))
|
|
if decErr != nil || len(data) == 0 {
|
|
return "", noop, errors.New("face-detect: image is neither an existing path nor valid base64")
|
|
}
|
|
|
|
tmp, createErr := os.CreateTemp("", "face-detect-*.img")
|
|
if createErr != nil {
|
|
return "", noop, fmt.Errorf("face-detect: create temp image: %w", createErr)
|
|
}
|
|
cleanup = func() { _ = os.Remove(tmp.Name()) }
|
|
if _, wErr := tmp.Write(data); wErr != nil {
|
|
_ = tmp.Close()
|
|
cleanup()
|
|
return "", noop, fmt.Errorf("face-detect: write temp image: %w", wErr)
|
|
}
|
|
if cErr := tmp.Close(); cErr != nil {
|
|
cleanup()
|
|
return "", noop, fmt.Errorf("face-detect: close temp image: %w", cErr)
|
|
}
|
|
return tmp.Name(), cleanup, nil
|
|
}
|
|
|
|
// lastErr wraps the C-API's per-ctx last-error buffer into a Go error.
|
|
func (f *FaceDetect) lastErr(op, subject string) error {
|
|
msg := strings.TrimSpace(CppLastError(f.ctxPtr))
|
|
if msg == "" {
|
|
msg = "no error detail"
|
|
}
|
|
return fmt.Errorf("face-detect: %s failed for %q: %s", op, subject, msg)
|
|
}
|
|
|
|
// goStringFromCPtr copies a NUL-terminated C string into Go memory. cptr is a
|
|
// malloc'd buffer the caller owns; release it via CppFreeString after the copy.
|
|
//
|
|
// The uintptr->Pointer conversion trips vet's unsafeptr check, which can't tell
|
|
// a C heap pointer from Go-managed memory. Safe here: the GC neither tracks nor
|
|
// moves the buffer and we dereference it immediately to copy the bytes out.
|
|
func goStringFromCPtr(cptr uintptr) string {
|
|
if cptr == 0 {
|
|
return ""
|
|
}
|
|
p := unsafe.Pointer(cptr) //nolint:govet // C-owned malloc'd buffer, not Go-GC memory (see doc above)
|
|
n := 0
|
|
for *(*byte)(unsafe.Add(p, n)) != 0 {
|
|
n++
|
|
}
|
|
return string(unsafe.Slice((*byte)(p), n))
|
|
}
|