Ir para o conteúdo

tempest_fastapi_sdk.faces

Detecção e reconhecimento facial em ONNX Runtime: detector, reconhecedor, alinhamento e pacotes de modelo.

« IA e visão computacional


FaceRecognizer

FaceRecognizer(
    *,
    pack: FaceModelPack | str = LIGHT_PACK,
    cache_dir: str | Path | None = None,
    detector_model: str | Path | None = None,
    recognizer_model: str | Path | None = None,
    threshold: float = DEFAULT_MATCH_THRESHOLD,
    min_face_pixels: int = MIN_FACE_PIXELS,
    num_threads: int = 1,
    max_concurrent: int = 2,
    idle_unload_seconds: float | None = None,
)

Detects, aligns and embeds faces.

Concurrent first calls build the models once, and a call in flight keeps them resident: unload_if_idle refuses while one runs, and an explicit unload waits for the last one to finish.

Attributes:

Name Type Description
pack FaceModelPack

Which models are in use.

threshold float

Similarity above which faces match.

idle_unload_seconds float | None

Idle time after which :meth:unload_if_idle releases the models.

Initialize the recognizer without loading anything.

Parameters:

Name Type Description Default
pack FaceModelPack | str

Model pack, by object or name.

LIGHT_PACK
cache_dir str | Path | None

Where packs are cached.

None
detector_model str | Path | None

Override the detection model path, skipping the pack download.

None
recognizer_model str | Path | None

Override the recognition model path.

None
threshold float

Similarity above which faces match.

DEFAULT_MATCH_THRESHOLD
min_face_pixels int

Smallest face worth embedding.

MIN_FACE_PIXELS
num_threads int

ONNX Runtime intra-op threads.

1
max_concurrent int

Inferences allowed at once.

2
idle_unload_seconds float | None

Idle time after which :meth:unload_if_idle releases the models.

None

Raises:

Type Description
ValueError

When threshold is outside 0..1, max_concurrent is below 1, or the pack name is unknown.

is_loaded property

is_loaded: bool

Whether both models are resident.

Returns:

Name Type Description
bool bool

True once loaded.

seconds_idle property

seconds_idle: float

Seconds since the models were last in use.

Reads 0.0 while an inference is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

load

load() -> None

Resolve and load both models, downloading the pack if needed.

Idempotent, and safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [faces] extra is absent.

unload

unload() -> None

Release both models.

While an inference is in flight the release waits for it: the last call to finish drops the sessions.

unload_if_idle

unload_if_idle() -> bool

Release the models when idle past idle_unload_seconds.

Returns:

Name Type Description
bool bool

Whether anything was unloaded — never while an inference

bool

is in flight, and never when no idle_unload_seconds was

bool

configured.

detect async

detect(image: str | Path | bytes) -> list[DetectedFace]

Find faces without embedding them.

Cheaper than :meth:recognize when the question is is there a face here — counting people, validating an upload, cropping a thumbnail — and it touches no biometric data.

Parameters:

Name Type Description Default
image str | Path | bytes

Path to an image, or its bytes.

required

Returns:

Type Description
list[DetectedFace]

list[DetectedFace]: Faces with boxes and landmarks, largest

list[DetectedFace]

first, embeddings empty.

recognize async

recognize(image: str | Path | bytes) -> list[DetectedFace]

Find faces and embed each one.

Parameters:

Name Type Description Default
image str | Path | bytes

Path to an image, or its bytes.

required

Returns:

Type Description
list[DetectedFace]

list[DetectedFace]: Faces, largest first, each carrying a

list[DetectedFace]

unit-length embedding. A face smaller than

list[DetectedFace]

min_face_pixels comes back with an empty embedding

list[DetectedFace]

rather than a vector describing its upscaling.

embed_face async

embed_face(image: str | Path | bytes) -> list[float]

Embed the largest face in an image.

The enrolment shape: one photo, one person, one vector.

Parameters:

Name Type Description Default
image str | Path | bytes

Path to an image, or its bytes.

required

Returns:

Type Description
list[float]

list[float]: The face vector, unit length.

Raises:

Type Description
ValueError

When no face was found, or the largest one is too small to embed. Both are refusals rather than empty results because enrolling nothing produces a profile that matches nobody, forever.

compare_faces

compare_faces(first: Sequence[float], second: Sequence[float]) -> float

Compare two face embeddings.

Parameters:

Name Type Description Default
first Sequence[float]

A face vector.

required
second Sequence[float]

Another face vector.

required

Returns:

Name Type Description
float float

Cosine similarity in [-1, 1]; 0.0 when either

float

vector is all zeros.

Raises:

Type Description
ValueError

When the vectors differ in length — different models produce incomparable vectors, and a low score would read as "not this person" when the truth is "this comparison means nothing".

ImportError

When NumPy is missing.

DEFAULT_MATCH_THRESHOLD module-attribute

DEFAULT_MATCH_THRESHOLD: float = 0.45

Cosine similarity above which two faces are called the same person.

Measured on the default pack: same person 0.898-0.991 (n=30), different people at most 0.285 (n=15). This sits in the middle of a 0.614-wide gap, so it is a safe default rather than a tuned one.

Raise it for anything that grants access. The measurement is on cooperative, front-facing photos; the error that matters there is admitting the wrong person, and a stricter threshold trades that against asking somebody to try again.

MIN_FACE_PIXELS module-attribute

MIN_FACE_PIXELS: int = 40

Smallest face side, in pixels, worth embedding.

Below this the aligned crop is mostly interpolation, and the embedding describes the upscaling more than the person. Reported rather than silently embedded, so a caller can tell "nobody recognisable" from "no face at all".

FaceDetector

FaceDetector(
    model: str | Path,
    *,
    score_threshold: float = DEFAULT_SCORE_THRESHOLD,
    nms_threshold: float = DEFAULT_NMS_THRESHOLD,
    num_threads: int = 1,
    providers: list[str] | None = None,
)

Detects faces and their five landmarks.

Attributes:

Name Type Description
score_threshold float

Minimum score to report a face.

nms_threshold float

Overlap at which boxes merge.

Initialize the detector without loading the model.

Parameters:

Name Type Description Default
model str | Path

Path to the SCRFD ONNX model.

required
score_threshold float

Minimum score to report.

DEFAULT_SCORE_THRESHOLD
nms_threshold float

Overlap at which boxes merge.

DEFAULT_NMS_THRESHOLD
num_threads int

ONNX Runtime intra-op threads.

1
providers list[str] | None

Execution providers. None uses CPU, which is what a web worker has.

None

Raises:

Type Description
ValueError

When either threshold is outside 0..1.

is_loaded property

is_loaded: bool

Whether the model is resident.

Returns:

Name Type Description
bool bool

True once loaded.

load

load() -> None

Build the inference session. Idempotent.

Raises:

Type Description
ImportError

When ONNX Runtime is missing — install the [faces] extra.

unload

unload() -> None

Release the model.

detect

detect(image: Image) -> list[DetectedFace]

Find every face in image.

Parameters:

Name Type Description Default
image Image

The image to search.

required

Returns:

Type Description
list[DetectedFace]

list[DetectedFace]: Faces with boxes, scores and landmarks,

list[DetectedFace]

ordered largest first — the subject of a photo is usually

list[DetectedFace]

the biggest face in it, so a caller taking [0] gets what

list[DetectedFace]

they meant.

Raises:

Type Description
ImportError

When the [faces] extra is absent.

DETECT_SIZE module-attribute

DETECT_SIZE: int = 640

Side of the square the image is letterboxed into before detection.

The models accept any size, but they were trained at 640 and a smaller canvas loses small faces while a larger one costs time without finding more. Fixed rather than exposed for that reason.

DEFAULT_SCORE_THRESHOLD module-attribute

DEFAULT_SCORE_THRESHOLD: float = 0.5

Minimum detector score for a face to be reported.

DEFAULT_NMS_THRESHOLD module-attribute

DEFAULT_NMS_THRESHOLD: float = 0.4

Overlap above which two boxes are treated as the same face.

MIN_DETECT_PIXELS module-attribute

MIN_DETECT_PIXELS: int = 320

Below this, the image is upscaled before detection.

A 112x112 crop of a face returned zero detections until it was enlarged. The detector letterboxes into 640 and its smallest anchor still expects a face well inside the frame, so a small image gives it almost nothing to work with.

TIGHT_CROP_MARGIN module-attribute

TIGHT_CROP_MARGIN: float = 0.2

Frame added around an image whose face may touch the edges.

Measured: the same 112x112 portrait went from zero detections to one with a 20% border. The detector needs context around a face, and a crop that was already tight has none to give.

align_face

align_face(image: Image, landmarks: Sequence[Sequence[float]]) -> Image

Warp a face into the recognizer's canonical 112x112 crop.

Parameters:

Name Type Description Default
image Image

The full image the face was found in.

required
landmarks Sequence[Sequence[float]]

Five (x, y) points in image coordinates.

required

Returns:

Type Description
Image

Image.Image: A 112x112 RGB image.

Raises:

Type Description
ValueError

When landmarks does not hold exactly five points.

ImportError

When Pillow or NumPy is missing — install the [faces] extra.

similarity_transform

similarity_transform(
    source: NDArray[float64], target: NDArray[float64]
) -> NDArray[float64]

Fit the similarity transform carrying source onto target.

Umeyama's closed-form solution: centre both point sets, take the SVD of their cross-covariance for the rotation, and read the scale off the singular values. The determinant correction is what keeps the result a rotation rather than a reflection — without it a face can come out mirrored, which the recognizer will happily embed as somebody else.

Parameters:

Name Type Description Default
source NDArray[float64]

(N, 2) points to move.

required
target NDArray[float64]

(N, 2) points to move them onto.

required

Returns:

Type Description
NDArray[float64]

npt.NDArray[np.float64]: A (2, 3) affine matrix.

Raises:

Type Description
ValueError

When the point sets differ in shape, or hold fewer than two points — a similarity transform is underdetermined below that.

ARCFACE_TEMPLATE module-attribute

ARCFACE_TEMPLATE: tuple[tuple[float, float], ...] = (
    (38.2946, 51.6963),
    (73.5318, 51.5014),
    (56.0252, 71.7366),
    (41.5493, 92.3655),
    (70.7299, 92.2041),
)

Where the five landmarks must land in a 112x112 crop.

Order: left eye, right eye, nose tip, left mouth corner, right mouth corner — the order the detector emits them in.

Ported from insightface's arcface_dst (insightface/utils/face_align.py). These are not tunable: they are the positions the recognition weights were trained against, so changing them degrades every embedding while leaving the code working. Pinned by test for that reason.

FACE_SIZE module-attribute

FACE_SIZE: int = 112

Side of the aligned crop, in pixels.

Fixed by the recognition models, not chosen: they declare a [N, 3, 112, 112] input and a different size would need a different template.

FaceModelPack dataclass

FaceModelPack(
    name: str,
    url: str,
    detector: str,
    recognizer: str,
    embedding_dimensions: int,
    megabytes: int,
)

A downloadable pair of detection and recognition models.

Attributes:

Name Type Description
name str

Pack name, used as the cache directory.

url str

Archive to fetch.

detector str

Detection model file inside the archive.

recognizer str

Recognition model file inside the archive.

embedding_dimensions int

Length of the vectors it produces.

megabytes int

Approximate size of the two models on disk, for the log line and the docs.

LIGHT_PACK module-attribute

LIGHT_PACK: FaceModelPack = FaceModelPack(
    name="buffalo_s",
    url=f"{_RELEASE}/buffalo_s.zip",
    detector="det_500m.onnx",
    recognizer="w600k_mbf.onnx",
    embedding_dimensions=512,
    megabytes=16,
)

The default pack: SCRFD-500M detection plus MobileFaceNet recognition.

Measured against the large pack with scripts/face_separation.py, over six generated portraits: same person 0.898-0.991 against 0.932-0.992, and different people at most 0.285 against 0.231 — a gap of 0.614 against 0.701. Detection ran at 23 ms per image against 178 ms on the machine that took the numbers, so read the ratio rather than the absolute times.

Twelve times smaller, seven times faster, for a gap that stays wide enough to leave the 0.45 threshold uncontested. The large pack earns its size where the margin narrows: on a tight 112x112 crop it found one face fewer than this one (n=29 against n=30), which is the kind of case its heavier detector exists for.

LARGE_PACK module-attribute

LARGE_PACK: FaceModelPack = FaceModelPack(
    name="buffalo_l",
    url=f"{_RELEASE}/buffalo_l.zip",
    detector="det_10g.onnx",
    recognizer="w600k_r50.onnx",
    embedding_dimensions=512,
    megabytes=191,
)

SCRFD-10G plus a ResNet50 recognizer.

Tighter separation than :data:LIGHT_PACK — a 0.701 gap against 0.614, measured by scripts/face_separation.py — at twelve times the size and roughly eight times the detection latency on the machine that took the numbers. Worth it when faces are small, poorly lit or partially turned: the cases where the margin matters, and where the lighter detector starts missing faces the heavier one still finds.

PACKS module-attribute

PACKS: Mapping[str, FaceModelPack] = {
    LIGHT_PACK.name: LIGHT_PACK,
    LARGE_PACK.name: LARGE_PACK,
}

Pack name to definition, for the CLI and for pack= by string.

ensure_models

ensure_models(
    pack: FaceModelPack | str = LIGHT_PACK, cache_dir: str | Path | None = None
) -> tuple[Path, Path]

Download a model pack if it is not cached, and return both paths.

Call it at build or startup time. Leaving it to the first request means one caller pays the download inside their timeout.

Parameters:

Name Type Description Default
pack FaceModelPack | str

Which pack to ensure.

LIGHT_PACK
cache_dir str | Path | None

Where to keep it. None uses :func:default_cache_dir.

None

Returns:

Type Description
tuple[Path, Path]

tuple[Path, Path]: (detector, recognizer) paths on disk.

Raises:

Type Description
OSError

When the download fails or the archive lacks a model.

resolve_pack

resolve_pack(pack: FaceModelPack | str) -> FaceModelPack

Accept a pack or its name.

Parameters:

Name Type Description Default
pack FaceModelPack | str

The pack, or a key of :data:PACKS.

required

Returns:

Name Type Description
FaceModelPack FaceModelPack

The resolved pack.

Raises:

Type Description
ValueError

When the name is unknown. The message lists the ones that exist, so a typo is one read away from fixed.

default_cache_dir

default_cache_dir() -> Path

Return where model packs are cached.

Honors TEMPEST_FACE_MODEL_DIR first so a deployment can point at a baked image layer or a mounted volume.

Returns:

Name Type Description
Path Path

The cache root. Not created here.

DetectedFace

Bases: BaseSchema

One face found in an image.

Attributes:

Name Type Description
box BoundingBox

Where it is.

confidence float

Detector score, 0..1.

landmarks list[list[float]]

The five (x, y) points, in detector order: left eye, right eye, nose, left mouth corner, right mouth corner.

embedding list[float]

The face vector, unit length. Empty when the caller asked to detect without recognising.

BoundingBox

Bases: BaseSchema

Where a face sits in the image, in pixels.

Attributes:

Name Type Description
left float

Left edge.

top float

Top edge.

right float

Right edge.

bottom float

Bottom edge.

width property

width: float

Box width in pixels.

Returns:

Name Type Description
float float

right - left.

height property

height: float

Box height in pixels.

Returns:

Name Type Description
float float

bottom - top.

FaceMatch

Bases: BaseSchema

A detected face matched against an enrolled profile.

Attributes:

Name Type Description
profile_id UUID

The profile that matched.

user_id UUID

Who it belongs to.

similarity float

Cosine similarity.

label str | None

The profile's label.