UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.
Python computer-visiondeep-learningface-alignmentface-analysisface-anonymizationface-anti-spoofingface-attributesface-detectionface-meshface-parsingface-quality-assessmentface-recognitionface-segmentationface-trackingfacial-landmarksgaze-estimationhead-pose-estimationonnxruntimeportrait-mattingpython
feat: Add get and set for cache dir (#80)
Yakhyokhuja Valikhujaev2a8cb54d312f
diff --git a/README.md b/README.mdindex 53bf6cd..7d0f394 100644--- a/README.md+++ b/README.md@@ -9,6 +9,7 @@[](https://pepy.tech/projects/uniface)[](https://yakhyo.github.io/uniface/)[](https://www.kaggle.com/yakhyokhuja/code)+[](https://discord.gg/wdzrjr7R5j)</div>@@ -71,7 +72,18 @@ Models are downloaded automatically on first use and verified via SHA-256.Default cache location: `~/.uniface/models`-You can override it with `UNIFACE_CACHE_DIR=/your/cache/path`+Override with the programmatic API or environment variable:++```python+from uniface import set_cache_dir, get_cache_dir++set_cache_dir('/data/models')+print(get_cache_dir()) # /data/models+```++```bash+export UNIFACE_CACHE_DIR=/data/models+```---@@ -209,6 +221,7 @@ Contributions are welcome. Please see [CONTRIBUTING.md](CONTRIBUTING.md).If you find this project useful, consider giving it a ⭐ on GitHub — it helps others discover it!Questions or feedback:+- Discord: https://discord.gg/wdzrjr7R5j- GitHub Issues: https://github.com/yakhyo/uniface/issues- DeepWiki Q&A: https://deepwiki.com/yakhyo/unifacediff --git a/docs/concepts/model-cache-offline.md b/docs/concepts/model-cache-offline.mdindex d9c1f16..80fdba1 100644--- a/docs/concepts/model-cache-offline.md+++ b/docs/concepts/model-cache-offline.md@@ -44,44 +44,57 @@ Default cache directory:## Custom Cache Directory-Specify a custom cache location:+Use the programmatic API to change the cache location at runtime:```python-from uniface.model_store import verify_model_weights-from uniface.constants import RetinaFaceWeights+from uniface import set_cache_dir, get_cache_dir-# Download to custom directory-model_path = verify_model_weights(- RetinaFaceWeights.MNET_V2,- root='./my_models'-)-print(f"Model at: {model_path}")+# 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 import RetinaFace+detector = RetinaFace() # Downloads to /data/models/```+Or set the `UNIFACE_CACHE_DIR` environment variable (see [Environment Variables](#environment-variables) below).+---## Pre-Download Models-Download models before deployment:+Download models before deployment using the concurrent downloader:```python-from uniface.model_store import verify_model_weights+from uniface import download_modelsfrom uniface.constants import (RetinaFaceWeights,ArcFaceWeights,AgeGenderWeights,)-# Download all needed models-models = [+# Download multiple models concurrently (up to 4 threads by default)+paths = download_models([RetinaFaceWeights.MNET_V2,ArcFaceWeights.MNET,AgeGenderWeights.DEFAULT,-]+])-for model in models:- path = verify_model_weights(model)- print(f"Downloaded: {path}")+for model, path in paths.items():+ print(f"{model.value} -> {path}")+```++Or download one at a time:++```python+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:@@ -115,7 +128,16 @@ print(f"Copy from: {path}")scp -r ~/.uniface/models/ user@offline-machine:~/.uniface/models/```-### 3. Use normally+### 3. Point to the cache (if non-default location)++```python+from uniface import set_cache_dir++# Only needed if the models are not at ~/.uniface/models/+set_cache_dir('/path/to/copied/models')+```++### 4. Use normally```python# Models load from local cache@@ -182,7 +204,12 @@ If a model fails verification, it's re-downloaded automatically.## Clear Cache-Remove cached models:+Find and remove cached models:++```python+from uniface import get_cache_dir+print(get_cache_dir()) # shows the active cache path+``````bash# Remove all cached models@@ -198,12 +225,19 @@ Models will be re-downloaded on next use.## Environment Variables-Set custom cache location via environment variable:+There are three equivalent ways to configure the cache directory:-```bash-export UNIFACE_CACHE_DIR=/path/to/custom/cache+**1. Programmatic API (recommended)**++```python+from uniface import set_cache_dir, get_cache_dir++set_cache_dir('/path/to/custom/cache')+print(get_cache_dir()) # /path/to/custom/cache```+**2. Direct environment variable (Python)**+```pythonimport osos.environ['UNIFACE_CACHE_DIR'] = '/path/to/custom/cache'@@ -212,6 +246,14 @@ from uniface import RetinaFacedetector = RetinaFace() # Uses custom cache```+**3. Shell environment variable**++```bash+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 Stepsdiff --git a/docs/concepts/overview.md b/docs/concepts/overview.mdindex 50b41fd..23f2300 100644--- a/docs/concepts/overview.md+++ b/docs/concepts/overview.md@@ -176,7 +176,7 @@ for face in faces:## Model Lifecycle1. **First use**: Model is downloaded from GitHub releases-2. **Cached**: Stored in `~/.uniface/models/`+2. **Cached**: Stored in `~/.uniface/models/` (configurable via `set_cache_dir()` or `UNIFACE_CACHE_DIR`)3. **Verified**: SHA-256 checksum validation4. **Loaded**: ONNX Runtime session created5. **Inference**: Hardware-accelerated execution@@ -185,6 +185,11 @@ for face in faces:# Models auto-download on first usedetector = RetinaFace() # Downloads if not cached+# Optionally configure cache location+from uniface import set_cache_dir, get_cache_dir+set_cache_dir('/data/models')+print(get_cache_dir()) # /data/models+# Or manually pre-downloadfrom uniface.model_store import verify_model_weightsfrom uniface.constants import RetinaFaceWeightsdiff --git a/docs/index.md b/docs/index.mdindex 80e2f07..7f8834c 100644--- a/docs/index.md+++ b/docs/index.md@@ -18,6 +18,7 @@ template: home.html[](https://github.com/yakhyo/uniface/actions)[](https://pepy.tech/projects/uniface)[](https://www.kaggle.com/yakhyokhuja/code)+[](https://discord.gg/wdzrjr7R5j)<img src="https://raw.githubusercontent.com/yakhyo/uniface/main/.github/logos/new/uniface_rounded_q80.webp" alt="UniFace - All-in-One Open-Source Face Analysis Library" style="max-width: 90%; margin: 1rem 0;">diff --git a/docs/models.md b/docs/models.mdindex df3947c..6f3271c 100644--- a/docs/models.md+++ b/docs/models.md@@ -349,10 +349,14 @@ Face anti-spoofing models for liveness detection. Detect if a face is real (liveModels are automatically downloaded and cached on first use.-- **Cache location**: `~/.uniface/models/`+- **Cache location**: `~/.uniface/models/` (configurable via `set_cache_dir()` or `UNIFACE_CACHE_DIR` env var)+- **Inspect cache path**: `get_cache_dir()` returns the resolved active path- **Verification**: Models are verified with SHA-256 checksums+- **Concurrent download**: `download_models([...])` fetches multiple models in parallel- **Manual download**: Use `python tools/download_model.py` to pre-download models+See [Model Cache & Offline Use](concepts/model-cache-offline.md) for full details.+---## Referencesdiff --git a/uniface/__init__.py b/uniface/__init__.pyindex dc654e0..33fb13d 100644--- a/uniface/__init__.py+++ b/uniface/__init__.py@@ -32,7 +32,7 @@ __version__ = '2.3.0'from uniface.face_utils import compute_similarity, face_alignmentfrom uniface.log import Logger, enable_logging-from uniface.model_store import verify_model_weights+from uniface.model_store import download_models, get_cache_dir, set_cache_dir, verify_model_weightsfrom uniface.visualization import draw_detections, vis_parsing_mapsfrom .analyzer import FaceAnalyzer@@ -111,9 +111,12 @@ __all__ = [# Utilities'Logger','compute_similarity',+ 'download_models','draw_detections','enable_logging','face_alignment',+ 'get_cache_dir',+ 'set_cache_dir','verify_model_weights','vis_parsing_maps',]diff --git a/uniface/model_store.py b/uniface/model_store.pyindex f910a46..a015744 100644--- a/uniface/model_store.py+++ b/uniface/model_store.py@@ -10,6 +10,7 @@ using SHA-256 checksums for integrity validation.from __future__ import annotations+from concurrent.futures import ThreadPoolExecutor, as_completedfrom enum import Enumimport hashlibimport os@@ -20,7 +21,47 @@ from tqdm import tqdmimport uniface.constants as constfrom uniface.log import Logger-__all__ = ['verify_model_weights']+__all__ = ['download_models', 'get_cache_dir', 'set_cache_dir', 'verify_model_weights']++_DEFAULT_CACHE_DIR = '~/.uniface/models'+_ENV_KEY = 'UNIFACE_CACHE_DIR'+++def get_cache_dir() -> str:+ """Get the current model cache directory path.++ Resolution order:+ 1. ``UNIFACE_CACHE_DIR`` environment variable (set via :func:`set_cache_dir` or directly).+ 2. Default: ``~/.uniface/models``.++ Returns:+ Absolute, expanded path to the cache directory.++ Example:+ >>> from uniface import get_cache_dir+ >>> print(get_cache_dir())+ '/home/user/.uniface/models'+ """+ return os.path.expanduser(os.environ.get(_ENV_KEY, _DEFAULT_CACHE_DIR))+++def set_cache_dir(path: str) -> None:+ """Set the model cache directory.++ This sets the ``UNIFACE_CACHE_DIR`` environment variable so that all+ subsequent model downloads and lookups use the new path.++ Args:+ path: Directory path for storing model weights.++ Example:+ >>> from uniface import set_cache_dir, get_cache_dir+ >>> set_cache_dir('/data/models')+ >>> print(get_cache_dir())+ '/data/models'+ """+ os.environ[_ENV_KEY] = path+ Logger.info(f'Cache directory set to: {path}')def verify_model_weights(model_name: Enum, root: str = '~/.uniface/models') -> str:@@ -51,8 +92,7 @@ def verify_model_weights(model_name: Enum, root: str = '~/.uniface/models') -> s'/home/user/.uniface/models/retinaface_mnet_v2.onnx'"""- root = os.getenv('UNIFACE_CACHE_DIR', root)- root = os.path.expanduser(root)+ root = get_cache_dir()os.makedirs(root, exist_ok=True)# Keep model_name as enum for dictionary lookup@@ -122,9 +162,50 @@ def verify_file_hash(file_path: str, expected_hash: str) -> bool:return actual_hash == expected_hash-if __name__ == '__main__':- model_names = [model.value for model in const.RetinaFaceWeights]+def download_models(model_names: list[Enum], max_workers: int = 4) -> dict[Enum, str]:+ """Download and verify multiple models concurrently.++ Uses a thread pool to download models in parallel, which is significantly+ faster when initializing several models at once.- # Download each model in the list- for model_name in model_names:- model_path = verify_model_weights(model_name)+ Args:+ model_names: List of model weight enum identifiers to download.+ max_workers: Maximum number of concurrent download threads. Defaults to 4.++ Returns:+ Mapping of each model enum to its local file path.++ Raises:+ RuntimeError: If any model download or verification fails.++ Example:+ >>> from uniface import download_models+ >>> from uniface.constants import RetinaFaceWeights, ArcFaceWeights+ >>> paths = download_models([RetinaFaceWeights.MNET_V2, ArcFaceWeights.RESNET])+ """+ results: dict[Enum, str] = {}+ errors: list[str] = []++ with ThreadPoolExecutor(max_workers=max_workers) as executor:+ future_to_model = {executor.submit(verify_model_weights, name): name for name in model_names}++ for future in as_completed(future_to_model):+ model = future_to_model[future]+ try:+ path = future.result()+ results[model] = path+ Logger.info(f'Ready: {model.value} -> {path}')+ except Exception as e:+ errors.append(f'{model.value}: {e}')+ Logger.error(f'Failed to download {model.value}: {e}')++ if errors:+ raise RuntimeError(f'Failed to download {len(errors)} model(s):\n' + '\n'.join(errors))++ Logger.info(f'All {len(results)} model(s) downloaded and verified')+ return results+++if __name__ == '__main__':+ for model in const.RetinaFaceWeights:+ model_path = verify_model_weights(model)diff --git a/uniface/types.py b/uniface/types.pyindex e7e0c1f..772cc55 100644--- a/uniface/types.py+++ b/uniface/types.py@@ -17,6 +17,7 @@ Note on mutability:from __future__ import annotationsfrom dataclasses import dataclass, fields+import jsonimport numpy as np@@ -182,6 +183,34 @@ class Face:"""Convert to dictionary."""return {f.name: getattr(self, f.name) for f in fields(self)}+ def to_json(self, indent: int | None = None) -> str:+ """Serialize the Face object to a JSON string.++ Converts numpy arrays to Python lists and numpy scalar types to+ native Python types so the result is fully JSON-serializable.++ Args:+ indent: Number of spaces for pretty-printing. None for compact output.++ Returns:+ JSON string representation of this Face object.++ Example:+ >>> face = faces[0]+ >>> print(face.to_json(indent=2))+ """+ data: dict = {}+ for f in fields(self):+ value = getattr(self, f.name)+ if isinstance(value, np.ndarray):+ value = value.tolist()+ elif isinstance(value, np.floating):+ value = float(value)+ elif isinstance(value, np.integer):+ value = int(value)+ data[f.name] = value+ return json.dumps(data, indent=indent)+@propertydef sex(self) -> str | None:"""Get gender as a string label (Female or Male)."""