Files
uniface/docs/concepts/model-cache-offline.md
Yakhyokhuja Valikhujaev 4d6f29a113 feat: Release v4.0.0 (#130)
* docs: Minor info changes

* refactor: Remove deprecated factory functions

Removes the 10 factory functions deprecated in v3.7.0:
create_detector, list_available_detectors, create_recognizer,
create_face_parser, create_gaze_estimator, create_head_pose_estimator,
create_landmarker, create_matting_model, create_spoofer,
create_attribute_predictor.

Instantiate model classes directly instead, e.g.
`from uniface.detection import SCRFD; SCRFD()`.

Also drops the now-unused typing_extensions dependency and updates
docstring examples that referenced the factories.

* refactor: Remove MODEL_URLS and MODEL_SHA256 back-compat mirrors

Use MODEL_REGISTRY instead of the MODEL_URLS and MODEL_SHA256 dicts in
uniface.constants.

* chore: Add .claude directory to gitignore

* ci: Deploy docs via GitHub Pages artifact instead of gh-pages branch

* feat: Add FaceAttribNet face state prediction model

Integrate Qualcomm's FaceAttribNet (Facial-Attribute-Detection) as a new
attribute model predicting five independent binary face states from a
face crop: left/right eye openness, eyeglasses, mask, and sunglasses.

- Add FaceAttribNet class with letterbox preprocessing (normalization is
  baked into the ONNX graph) and multi-label FaceStateResult output
- Register FaceAttribNetWeights with dynamic-batch ONNX weights (opset 17)
- Enrich Face with left_eye_open, right_eye_open, eyeglasses, mask,
  and sunglasses fields
- Rename AttributeResult to DemographyResult and DDAMFNWeights to
  EmotionWeights so 'attribute' unambiguously means the model category
- Add tests and docs

* docs: Add face attributes notebook, demo assets, and README updates

* feat: Add CenterFace face detection model

* docs: Add CONTEXT.md glossary and ADRs for v4 naming decisions

ADR-0001: Face.landmarks keeps its v3 name for the 5-point set; the
future dense-landmark slot will be Face.dense_landmarks.
ADR-0002: Attribute stays the per-face predictor base class name;
FaceAnalyzer(attributes=...) is unchanged.

* refactor: Rename FaceAnalyzer attributes parameter to predictors

The pipeline parameter names the role (per-face predictors), so future
head pose, gaze, spoofing, and quality models can be passed without the
semantic mismatch of being listed as attributes. The Attribute base
class keeps its name per ADR-0002.

BREAKING CHANGE: FaceAnalyzer(attributes=...) is now
FaceAnalyzer(predictors=...); FaceAnalyzer.attributes is now
FaceAnalyzer.predictors.

* docs: Update docs and notebooks for predictors parameter rename

* docs: Remove CONTEXT.md

* docs: Restore README badges

* docs: Remove ADR folder

* refactor: Rename Attribute base class to BaseAttribute

* docs: Replace thick README separators with heading underlines

* docs: Put README tagline in a callout

* fix: Use predictors= in the analyze tool

* refactor: Make supports_landmarks a class attribute on BaseDetector

Replaces the private _supports_landmarks instance flag and its read-only
property with a plain class attribute, mirroring supports_alignment. Every
detector set the flag to True in __init__, so the False default never
survived and the hasattr guard in the property was dead weight.

Also drops a stale Attributes entry in RetinaFace for a field that no
longer exists, and removes comments that restated the call beneath them.

* docs: Normalize docstring markup and document missing raises

Audited every docstring and comment in uniface/ against the detection
package, which is the most internally consistent one.

- Replace 13 Sphinx roles and 159 RST double-backticks with markdown
  backticks; nothing renders docstrings, there is no Sphinx, and mkdocs
  has no mkdocstrings plugin
- Rewrite 59 legacy typing generics (List, Tuple, Optional, Union) to
  PEP 585, each checked against the real signature rather than
  mechanically substituted
- Add Raises sections to download_file, compute_similarity and
  parse_with_inverse, which raised undocumented exceptions
- Drop the RuntimeError Raises block from six abstract _initialize_model
  methods whose body raises NotImplementedError; the contract belongs to
  the implementer and is now stated as prose
- Fold Properties into Attributes with a Read-only prefix, singularize
  Examples, and fix the copyright year in faceattribnet

No executable line changed; the bulk pass rewrote only string and comment
tokens matched by byte offset.

* fix: Raise ValueError instead of asserting in estimate_norm

Both input checks used bare assert statements, which python -O strips.
The docstring promised AssertionError as part of the contract, so under an
optimized build the validation silently disappeared and an unsupported
image_size flowed into the alignment maths instead of failing fast.

Both are now ValueError, and the messages report the offending value.

* docs: Replace RST double-backticks in face_utils

* docs: Document Raises on every model class

The detection package documents ValueError and RuntimeError on the class
docstring; no model class in any other package did, even though they all
call verify_model_weights in __init__ and reach an _initialize_model that
wraps session creation in RuntimeError.

Verified per class before adding: each target reaches both raise sites,
inheriting _initialize_model from its base where it does not define one.

* fix: Replace the last two bare asserts with explicit raises

python -O strips assert statements, so both checks silently disappeared in
optimized builds. BaseRecognizer would then accept a multi-output model and
mis-slice its results, and get_meanface_info would build neighbour tables
from a meanface of the wrong length.

Behaviour is unchanged in normal builds: the recognizer check already sat
inside the try that re-raises as RuntimeError, and the meanface check now
raises the ValueError its docstring already documented.

No bare asserts remain in uniface/.

* style: Put multi-line docstring summaries on the first line

Card 6 of the docstring audit: class docstrings opened two different ways,
45 with a leading newline and 37 on the same line as the quotes.

Settled by the repo's own config rather than by taste. pyproject already
declares pydocstyle convention = google, under which ruff resolves D212
(multi-line-summary-first-line) as the active rule and explicitly ignores
the incompatible D213. Same-line was therefore already the declared
standard, even though the detection package -- the audit's exemplar -- sat
on the other side of the split.

Applied with ruff --fix, then the summaries that ended up glued to their
description got the blank line D205 wants.

* style: Put multi-line docstring summaries on the first line (constants, test_utils)

Same D212/D205 pass as the previous commit, applied to the two files that
were held back from it.

* build: Enforce D205 and D212 in ruff

The docstring audit found the opening style split 45/37 with nothing to
hold it in place: pyproject declared pydocstyle convention = google, but D
was absent from select, so the convention setting was inert.

Selecting the two rules the codebase now satisfies makes the decision
checkable instead of conventional. The rest of D is left off deliberately
-- D100 alone would flag 63 files, since this project's convention is to
have no module docstrings.

* feat: Add BlazeFace detector and MediaPipe Face Mesh landmarker

BlazeFace is MediaPipe's short-range SSD face detector: two anchor grids
over a 128x128 letterboxed image, decoded with MediaPipe's weighted NMS
where overlapping candidates are score-averaged rather than discarded.

It emits 6 MediaPipe keypoints, not the 5-point alignment template, so
BaseDetector gains a supports_alignment flag. It is True everywhere else
and False only here. FaceAnalyzer checks it and disables recognition with
a warning instead of producing broken embeddings, and estimate_norm's
error now names the constraint when a caller tries to align anyway.

FaceMesh predicts 468 dense 3D landmarks from a face crop and is
detector-agnostic: the ROI follows MediaPipe's recipe, a square region at
1.5x the detector box rotated so the eye line is horizontal, built from
whichever two eye points the detector provides. Every face in an image
runs in one session call. roi_from_box and warp_roi are public so
video-mode tracking can be built on top.

Also adds FaceMeshResult, draw_mesh with full and partial tessellations,
weight entries for both models, the facemesh and facestate tools, example
notebook 15, and tests for both models.

Tessellation tables are vendored from PINTO0309/facemesh_onnx_tensorrt
(Apache-2.0); provenance is recorded in docs/license-attribution.md.

* docs: List BlazeFace and Face Mesh in the remaining model indexes

The feature commit updated the detection and landmarks module pages, the
model zoo and the concept pages, but four summary listings still predated
both models:

- README examples table stopped at notebook 14
- README training-dataset table omitted both
- quickstart model summary omitted both
- index.md feature cards described detection as 5-point only, which
  BlazeFace's 6 keypoints contradict

* feat: Add MediaPipe Face Landmarker, a 478-point mesh with irises

Google's Face Landmarker is the successor to Face Mesh: one network predicting
478 landmarks from a 256x256 crop, where the first 468 keep the Face Mesh
topology and ordering and the last ten are the irises. It ships in the Tasks
API bundle; the earlier 478-point attention model is not ported, since it needs
three MediaPipe-only TFLite custom ops that no standard runtime can load.

FaceMesh needs no logic change to serve it. Input size and landmark count were
already read from the ONNX graph, so 192->256 and 468->478 are absorbed at load
time. Verified end to end at 0.007% of inter-ocular distance against MediaPipe's
own pipeline, with the existing ROI recipe unchanged - Google's model card
specifies the same 25% per-side margin the default already used.

Iris membership follows MediaPipe's own convention: the result stays a flat
array and the region lives in named constants next to the topology it indexes,
rather than becoming accessors on FaceMeshResult. draw_mesh renders the irises
distinctly, so the library and tools/facemesh.py agree by construction.

BREAKING CHANGE: FaceMeshWeights.DEFAULT is replaced by V1_468 and V2_478.
Default behaviour is unchanged - the constructor still loads the 468-point
model - but code naming DEFAULT explicitly must be updated. Every other
multi-variant weights enum already names its members descriptively.

* feat: Add Hugging Face mirror fallback for weight downloads

* docs: Document the Hugging Face mirror fallback

* fix: Resolve bugs found in whole-codebase review

* refactor: Publish validate_image and normalize line endings

* fix: Guarantee weighted NMS terminates

* refactor: Make model constructors keyword-only

* refactor: Read input_size from the ONNX model

* fix: Normalize and validate attribute input_size

* refactor: Replace detector **kwargs with explicit options

* fix: Reject unusable images in BlazeFace and FaceMesh

* feat: Make detector capability flags opt-in

* fix: Show every populated face state in Face repr

* docs: Clarify inline comments

* docs: Update docs and notebooks for v4

* refactor: Make remaining public constructors keyword-only

* feat: Export BaseAttribute and document custom predictors

* test: Cover FaceAnalyzer predictors

* fix: Pin the Hugging Face mirror to an immutable revision

* docs: Add changelog with v4 migration guide

* ci: Deploy release docs via the Pages artifact flow

* build: Require setuptools 77 for the SPDX license field

* docs: Fix anchors, dataset table, and tool options

* chore: Release v4.0.0rc1

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-04 02:47:26 +09:00

5.8 KiB

Model Cache & Offline Use

UniFace automatically downloads and caches models. This page explains how model management works.


Automatic Download

Models are downloaded on first use:

from uniface.detection import RetinaFace

# First run: downloads model to cache
detector = RetinaFace()  # ~3.5 MB download

# Subsequent runs: loads from cache
detector = RetinaFace()  # Instant

Weights come from GitHub Releases, with a Hugging Face mirror as an automatic fallback when GitHub is unreachable. There is nothing to configure, and no Hugging Face token is needed.


Cache Location

Default cache directory:

~/.uniface/models/

Example structure:

~/.uniface/models/
├── retinaface_mnet_v2.onnx
├── arcface_mnet.onnx
├── 2d_106.onnx
├── gaze_resnet34.onnx
├── parsing_resnet18.onnx
└── ...

Custom Cache Directory

Use the programmatic API to change the cache location at runtime:

from uniface.model_store import get_cache_dir, set_cache_dir

# Set a custom cache directory
set_cache_dir('/data/models')

# Verify the current path
print(get_cache_dir())  # /data/models

# All subsequent model loads use the new directory
from uniface.detection import RetinaFace
detector = RetinaFace()  # Downloads to /data/models/

Or set the UNIFACE_CACHE_DIR environment variable (see Environment Variables below).


Pre-Download Models

Download models before deployment using the concurrent downloader:

from uniface.model_store import download_models
from uniface.constants import (
    RetinaFaceWeights,
    ArcFaceWeights,
    AgeGenderWeights,
)

# Download multiple models concurrently (defaults to min(CPU count, 8) threads)
paths = download_models([
    RetinaFaceWeights.MNET_V2,
    ArcFaceWeights.MNET,
    AgeGenderWeights.DEFAULT,
])

for model, path in paths.items():
    print(f"{model.value} -> {path}")

Or download one at a time:

from uniface.model_store import verify_model_weights
from uniface.constants import RetinaFaceWeights

path = verify_model_weights(RetinaFaceWeights.MNET_V2)
print(f"Downloaded: {path}")

Or use the CLI tool:

python tools/download_model.py

Offline Use

For air-gapped or offline environments:

1. Pre-download models

On a connected machine:

from uniface.model_store import verify_model_weights
from uniface.constants import RetinaFaceWeights

path = verify_model_weights(RetinaFaceWeights.MNET_V2)
print(f"Copy from: {path}")

2. Copy to target machine

# Copy the entire cache directory
scp -r ~/.uniface/models/ user@offline-machine:~/.uniface/models/

3. Point to the cache (if non-default location)

from uniface.model_store import set_cache_dir

# Only needed if the models are not at ~/.uniface/models/
set_cache_dir('/path/to/copied/models')

4. Use normally

# Models load from local cache
from uniface.detection import RetinaFace
detector = RetinaFace()  # No network required

Model Verification

Models are verified with SHA-256 checksums:

from uniface.constants import MODEL_REGISTRY, RetinaFaceWeights

# Check expected checksum
expected = MODEL_REGISTRY[RetinaFaceWeights.MNET_V2].sha256
print(f"Expected SHA256: {expected}")

If a model fails verification, it's re-downloaded automatically. The same checksum is enforced whichever source served the file, so a corrupted or stale mirror falls through to the other source instead of being cached.


Available Models

Detection Models

Model Size Download
RetinaFace MNET_025 1.7 MB
RetinaFace MNET_V2 3.5 MB
RetinaFace RESNET34 56 MB
SCRFD 500M 2.5 MB
SCRFD 10G 17 MB
YOLOv5n-Face 11 MB
YOLOv5s-Face 28 MB
YOLOv5m-Face 82 MB
YOLOv8-Lite-S 7.4 MB
YOLOv8n-Face 12 MB

Recognition Models

Model Size Download
ArcFace MNET 8 MB
ArcFace RESNET 166 MB
MobileFace MNET_V2 4 MB
SphereFace SPHERE20 50 MB

Other Models

Model Size Download
Landmark106 14 MB
PIPNet WFLW-98 47 MB
PIPNet 300W+CelebA-68 46 MB
AgeGender 8 MB
FairFace 44 MB
Gaze ResNet34 82 MB
BiSeNet ResNet18 51 MB
MiniFASNet V2 1.2 MB

Clear Cache

Find and remove cached models:

from uniface.model_store import get_cache_dir
print(get_cache_dir())  # shows the active cache path
# Remove all cached models
rm -rf ~/.uniface/models/

# Remove specific model
rm ~/.uniface/models/retinaface_mnet_v2.onnx

Models will be re-downloaded on next use.


Environment Variables

There are three equivalent ways to configure the cache directory:

1. Programmatic API (recommended)

from uniface.model_store import get_cache_dir, set_cache_dir

set_cache_dir('/path/to/custom/cache')
print(get_cache_dir())  # /path/to/custom/cache

2. Direct environment variable (Python)

import os
os.environ['UNIFACE_CACHE_DIR'] = '/path/to/custom/cache'

from uniface.detection import RetinaFace
detector = RetinaFace()  # Uses custom cache

3. Shell environment variable

export UNIFACE_CACHE_DIR=/path/to/custom/cache

All three methods set the same UNIFACE_CACHE_DIR environment variable under the hood. get_cache_dir() always returns the resolved path.


Next Steps