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 FAISS vector DB support for fast search (#86)
Yakhyokhuja Valikhujaev87e496d1f5c1
diff --git a/README.md b/README.mdindex b59768c..ddeb4a9 100644--- a/README.md+++ b/README.md@@ -32,6 +32,7 @@- **Face Parsing** — BiSeNet semantic segmentation (19 classes), XSeg face masking- **Gaze Estimation** — Real-time gaze direction with MobileGaze- **Attribute Analysis** — Age, gender, race (FairFace), and emotion+- **Vector Indexing** — FAISS-backed embedding store for fast multi-identity search- **Anti-Spoofing** — Face liveness detection with MiniFASNet- **Face Anonymization** — 5 blur methods for privacy protection- **Hardware Acceleration** — ARM64 (Apple Silicon), CUDA (NVIDIA), CPU@@ -59,6 +60,12 @@ git clone https://github.com/yakhyo/uniface.gitcd uniface && pip install -e .```+**FAISS vector indexing**++```bash+pip install faiss-cpu # or faiss-gpu for CUDA+```+**Optional dependencies**- Emotion model uses TorchScript and requires `torch`:`pip install torch` (choose the correct build for your OS/CUDA)diff --git a/assets/einstein/img_0.png b/assets/einstein/img_0.pngnew file mode 100644index 0000000..8277290Binary files /dev/null and b/assets/einstein/img_0.png differdiff --git a/docs/concepts/overview.md b/docs/concepts/overview.mdindex a39e00e..46d5a9d 100644--- a/docs/concepts/overview.md+++ b/docs/concepts/overview.md@@ -32,6 +32,10 @@ graph TBTRK[BYTETracker]end+ subgraph Indexing+ IDX[FAISS Vector Store]+ end+subgraph OutputFACE[Face Objects]end@@ -45,6 +49,7 @@ graph TBDET --> SPOOFDET --> PRIVDET --> TRK+ REC --> IDXREC --> FACELMK --> FACEATTR --> FACE@@ -57,12 +62,14 @@ graph TB### 1. ONNX-First-All models use ONNX Runtime for inference:+UniFace runs inference primarily via ONNX Runtime for core components:- **Cross-platform**: Same models work on macOS, Linux, Windows- **Hardware acceleration**: Automatic selection of optimal provider- **Production-ready**: No Python-only dependencies for inference+Some optional components (e.g., emotion TorchScript, torchvision NMS) require PyTorch.+### 2. Minimal DependenciesCore dependencies are kept minimal:@@ -114,6 +121,7 @@ uniface/├── gaze/ # Gaze estimation├── spoofing/ # Anti-spoofing├── privacy/ # Face anonymization+├── indexing/ # Vector indexing (FAISS)├── types.py # Dataclasses (Face, GazeResult, etc.)├── constants.py # Model weights and URLs├── model_store.py # Model download and cachingdiff --git a/docs/index.md b/docs/index.mdindex 2c29a93..08883ac 100644--- a/docs/index.md+++ b/docs/index.md@@ -74,31 +74,35 @@ Face liveness detection with MiniFASNet to prevent fraud.Face anonymization with 5 blur methods for privacy protection.</div>+<div class="feature-card" markdown>+### :material-database-search: Vector Indexing+FAISS-backed embedding store for fast multi-identity face search.+</div>+</div>---## Installation-=== "Standard"-- ```bash- pip install uniface- ```--=== "GPU (CUDA)"+UniFace runs inference primarily via **ONNX Runtime**; some optional components (e.g., emotion TorchScript, torchvision NMS) require **PyTorch**.- ```bash- pip install uniface[gpu]- ```+**Standard**+```bash+pip install uniface+```-=== "From Source"+**GPU (CUDA)**+```bash+pip install uniface[gpu]+```- ```bash- git clone https://github.com/yakhyo/uniface.git- cd uniface- pip install -e .- ```+**From Source**+```bash+git clone https://github.com/yakhyo/uniface.git+cd uniface+pip install -e .+```---diff --git a/docs/installation.md b/docs/installation.mdindex 880f666..477d586 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -55,11 +55,10 @@ pip install uniface[gpu]**Requirements:**-- CUDA 11.x or 12.x-- cuDNN 8.x+- `uniface[gpu]` automatically installs `onnxruntime-gpu`. Requirements depend on the ORT version and execution provider.!!! info "CUDA Compatibility"- See [ONNX Runtime GPU requirements](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html) for detailed compatibility matrix.+ See the [ONNX Runtime GPU compatibility matrix](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html) for matching CUDA and cuDNN versions.Verify GPU installation:@@ -71,6 +70,19 @@ print("Available providers:", ort.get_available_providers())---+### FAISS Vector Indexing++For fast multi-identity face search using a FAISS index:++```bash+pip install faiss-cpu # CPU+pip install faiss-gpu # NVIDIA GPU (CUDA)+```++See the [Indexing module](modules/indexing.md) for usage.++---+### CPU-Only (All Platforms)```bash@@ -107,12 +119,20 @@ UniFace has minimal dependencies:|---------|---------|| `numpy` | Array operations || `opencv-python` | Image processing |-| `onnx` | ONNX model format support || `onnxruntime` | Model inference || `scikit-image` | Geometric transforms || `requests` | Model download || `tqdm` | Progress bars |+**Optional:**++| Package | Install extra | Purpose |+|---------|---------------|---------|+| `faiss-cpu` / `faiss-gpu` | `pip install faiss-cpu` | FAISS vector indexing |+| `onnxruntime-gpu` | `uniface[gpu]` | CUDA acceleration |+| `torch` | `pip install torch` | Emotion model uses TorchScript |+| `torchvision` | `pip install torchvision` | Faster NMS for YOLO detectors |+---## Verify Installationdiff --git a/docs/modules/indexing.md b/docs/modules/indexing.mdnew file mode 100644index 0000000..f5c4312--- /dev/null+++ b/docs/modules/indexing.md@@ -0,0 +1,172 @@+# Indexing++FAISS-backed vector store for fast similarity search over embeddings.++!!! info "Optional dependency"+ ```bash+ pip install faiss-cpu+ ```++---++## FAISS++```python+from uniface.indexing import FAISS+```++A thin wrapper around a FAISS `IndexFlatIP` (inner-product) index. Vectors+**must** be L2-normalised before adding so that inner product equals cosine+similarity. The store does not normalise internally.++Each vector is paired with a metadata `dict` that can carry any+JSON-serialisable payload (person ID, name, source path, etc.).++### Constructor++```python+store = FAISS(embedding_size=512, db_path="./vector_index")+```++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `embedding_size` | `int` | `512` | Dimension of embedding vectors |+| `db_path` | `str` | `"./vector_index"` | Directory for persisting index and metadata |++---++### Methods++#### `add(embedding, metadata)`++Add a single embedding with associated metadata.++```python+store.add(embedding, {"person_id": "alice", "source": "photo.jpg"})+```++| Parameter | Type | Description |+|-----------|------|-------------|+| `embedding` | `np.ndarray` | L2-normalised embedding vector |+| `metadata` | `dict[str, Any]` | Arbitrary JSON-serialisable key-value pairs |++---++#### `search(embedding, threshold=0.4)`++Find the closest match for a query embedding.++```python+result, similarity = store.search(query_embedding, threshold=0.4)+if result:+ print(result["person_id"], similarity)+```++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `embedding` | `np.ndarray` | — | L2-normalised query vector |+| `threshold` | `float` | `0.4` | Minimum cosine similarity to accept a match |++**Returns:** `(metadata, similarity)` if a match is found, or `(None, similarity)` when below threshold or the index is empty.++---++#### `remove(key, value)`++Remove all entries where `metadata[key] == value` and rebuild the index.++```python+removed = store.remove("person_id", "bob")+print(f"Removed {removed} entries")+```++| Parameter | Type | Description |+|-----------|------|-------------|+| `key` | `str` | Metadata key to match |+| `value` | `Any` | Value to match |++**Returns:** Number of entries removed.++---++#### `save()`++Persist the FAISS index and metadata to disk.++```python+store.save()+```++Writes two files to `db_path`:++- `faiss_index.bin` — binary FAISS index+- `metadata.json` — JSON array of metadata dicts++---++#### `load()`++Load a previously saved index and metadata.++```python+store = FAISS(db_path="./vector_index")+loaded = store.load() # True if files exist+```++**Returns:** `True` if loaded successfully, `False` if files are missing.++**Raises:** `RuntimeError` if files exist but cannot be read.++---++### Properties++| Property | Type | Description |+|----------|------|-------------|+| `size` | `int` | Number of vectors in the index |+| `len(store)` | `int` | Same as `size` |++---++## Example: End-to-End++```python+import cv2+from uniface.detection import RetinaFace+from uniface.recognition import ArcFace+from uniface.indexing import FAISS++detector = RetinaFace()+recognizer = ArcFace()++# Build+store = FAISS(db_path="./my_index")++image = cv2.imread("alice.jpg")+faces = detector.detect(image)+embedding = recognizer.get_normalized_embedding(image, faces[0].landmarks)+store.add(embedding, {"person_id": "alice"})+store.save()++# Search+store2 = FAISS(db_path="./my_index")+store2.load()++query = cv2.imread("unknown.jpg")+faces = detector.detect(query)+emb = recognizer.get_normalized_embedding(query, faces[0].landmarks)++result, sim = store2.search(emb)+if result:+ print(f"Matched: {result['person_id']} (similarity: {sim:.3f})")+else:+ print(f"No match (similarity: {sim:.3f})")+```++---++## See Also++- [Face Search Recipe](../recipes/face-search.md) - Building and querying indexes+- [Recognition Module](recognition.md) - Embedding extraction+- [Thresholds Guide](../concepts/thresholds-calibration.md) - Tuning similarity thresholdsdiff --git a/docs/quickstart.md b/docs/quickstart.mdindex cb7522f..a2d0138 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -475,6 +475,7 @@ from uniface.privacy import BlurFacefrom uniface.spoofing import MiniFASNetfrom uniface.tracking import BYTETrackerfrom uniface.analyzer import FaceAnalyzer+from uniface.indexing import FAISS # pip install faiss-cpufrom uniface.draw import draw_detections, draw_tracks```diff --git a/docs/recipes/face-search.md b/docs/recipes/face-search.mdindex 1ff7729..82c200d 100644--- a/docs/recipes/face-search.md+++ b/docs/recipes/face-search.md@@ -1,179 +1,166 @@# Face Search-Build a face search system for finding people in images.+Find and identify people in images and video streams.-!!! note "Work in Progress"- This page contains example code patterns. Test thoroughly before using in production.+UniFace supports two search approaches:++| Approach | Use case | Tool |+| -------------------- | ------------------------------------------------ | ----------------------- |+| **Reference search** | "Is this specific person in the video?" | `tools/search.py` |+| **Vector search** | "Who is this?" against a database of known faces | `tools/faiss_search.py` |----## Basic Face Database+## Reference Search (single image)++Compare every detected face against a single reference photo:```python-import numpy as npimport cv2-from pathlib import Path+import numpy as npfrom uniface.detection import RetinaFacefrom uniface.recognition import ArcFace+from uniface.face_utils import compute_similarity++detector = RetinaFace()+recognizer = ArcFace()++ref_image = cv2.imread("reference.jpg")+ref_faces = detector.detect(ref_image)+ref_embedding = recognizer.get_normalized_embedding(ref_image, ref_faces[0].landmarks)-class FaceDatabase:- def __init__(self):- self.detector = RetinaFace()- self.recognizer = ArcFace()- self.embeddings = {}-- def add_face(self, person_id, image):- """Add a face to the database."""- faces = self.detector.detect(image)- if not faces:- raise ValueError(f"No face found for {person_id}")-- face = max(faces, key=lambda f: f.confidence)- embedding = self.recognizer.get_normalized_embedding(image, face.landmarks)- self.embeddings[person_id] = embedding- return True-- def search(self, image, threshold=0.6):- """Search for faces in an image."""- faces = self.detector.detect(image)- results = []-- for face in faces:- embedding = self.recognizer.get_normalized_embedding(image, face.landmarks)-- best_match = None- best_similarity = -1-- for person_id, db_embedding in self.embeddings.items():- similarity = np.dot(embedding, db_embedding.T)[0][0]- if similarity > best_similarity:- best_similarity = similarity- best_match = person_id-- results.append({- 'bbox': face.bbox,- 'match': best_match if best_similarity >= threshold else None,- 'similarity': best_similarity- })-- return results-- def save(self, path):- """Save database to file."""- np.savez(path, embeddings=dict(self.embeddings))-- def load(self, path):- """Load database from file."""- data = np.load(path, allow_pickle=True)- self.embeddings = data['embeddings'].item()--# Usage-db = FaceDatabase()--# Add faces-for image_path in Path("known_faces/").glob("*.jpg"):- person_id = image_path.stem- image = cv2.imread(str(image_path))- try:- db.add_face(person_id, image)- print(f"Added: {person_id}")- except ValueError as e:- print(f"Skipped: {e}")--# Save database-db.save("face_database.npz")--# Searchquery_image = cv2.imread("group_photo.jpg")-results = db.search(query_image)+faces = detector.detect(query_image)++for face in faces:+ embedding = recognizer.get_normalized_embedding(query_image, face.landmarks)+ sim = compute_similarity(ref_embedding, embedding)-for r in results:- if r['match']:- print(f"Found: {r['match']} (similarity: {r['similarity']:.3f})")+ label = f"Match ({sim:.2f})" if sim > 0.4 else f"Unknown ({sim:.2f})"+ print(label)+```++**CLI tool:**++```bash+python tools/search.py --reference ref.jpg --source video.mp4+python tools/search.py --reference ref.jpg --source 0 # webcam```----## Visualization+## Vector Search (FAISS index)-```python-import cv2+For identifying faces against a database of many known people, use the+[`FAISS`](../modules/indexing.md) vector store.-def visualize_search_results(image, results):- """Draw search results on image."""- for r in results:- x1, y1, x2, y2 = map(int, r['bbox'])+!!! info "Install extra"+`bash+ pip install faiss-cpu+ `- if r['match']:- color = (0, 255, 0) # Green for match- label = f"{r['match']} ({r['similarity']:.2f})"- else:- color = (0, 0, 255) # Red for unknown- label = f"Unknown ({r['similarity']:.2f})"+### Build an index- cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)- cv2.putText(image, label, (x1, y1 - 10),- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)+Organise face images in person sub-folders:- return image+```+dataset/+├── alice/+│ ├── 001.jpg+│ └── 002.jpg+├── bob/+│ └── 001.jpg+└── charlie/+ ├── 001.jpg+ └── 002.jpg+```-# Usage-results = db.search(image)-annotated = visualize_search_results(image.copy(), results)-cv2.imwrite("search_result.jpg", annotated)+```python+import cv2+from pathlib import Path+from uniface.detection import RetinaFace+from uniface.recognition import ArcFace+from uniface.indexing import FAISS++detector = RetinaFace()+recognizer = ArcFace()+store = FAISS(db_path="./my_index")++for person_dir in sorted(Path("dataset").iterdir()):+ if not person_dir.is_dir():+ continue+ for img_path in person_dir.glob("*.jpg"):+ image = cv2.imread(str(img_path))+ faces = detector.detect(image)+ if faces:+ emb = recognizer.get_normalized_embedding(image, faces[0].landmarks)+ store.add(emb, {"person_id": person_dir.name, "source": str(img_path)})++store.save()+print(f"Index saved: {store}")```----+**CLI tool:**++```bash+python tools/faiss_search.py build --faces-dir dataset/ --db-path ./my_index+```-## Real-Time Search+### Search against the index```pythonimport cv2+from uniface.detection import RetinaFace+from uniface.recognition import ArcFace+from uniface.indexing import FAISS++detector = RetinaFace()+recognizer = ArcFace()-def realtime_search(db):- """Real-time face search from webcam."""- cap = cv2.VideoCapture(0)+store = FAISS(db_path="./my_index")+store.load()- while True:- ret, frame = cap.read()- if not ret:- break+image = cv2.imread("query.jpg")+faces = detector.detect(image)- results = db.search(frame, threshold=0.5)+for face in faces:+ embedding = recognizer.get_normalized_embedding(image, face.landmarks)+ result, similarity = store.search(embedding, threshold=0.4)- for r in results:- x1, y1, x2, y2 = map(int, r['bbox'])+ if result:+ print(f"Matched: {result['person_id']} ({similarity:.2f})")+ else:+ print(f"Unknown ({similarity:.2f})")+```- if r['match']:- color = (0, 255, 0)- label = r['match']- else:- color = (0, 0, 255)- label = "Unknown"+**CLI tool:**- cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)- cv2.putText(frame, label, (x1, y1 - 10),- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)+```bash+python tools/faiss_search.py run --db-path ./my_index --source video.mp4+python tools/faiss_search.py run --db-path ./my_index --source 0 # webcam+```++### Manage the index++```python+from uniface.indexing import FAISS- cv2.imshow("Face Search", frame)+store = FAISS(db_path="./my_index")+store.load()- if cv2.waitKey(1) & 0xFF == ord('q'):- break+print(f"Total vectors: {len(store)}")- cap.release()- cv2.destroyAllWindows()+removed = store.remove("person_id", "bob")+print(f"Removed {removed} entries")-# Usage-db = FaceDatabase()-db.load("face_database.npz")-realtime_search(db)+store.save()```---## See Also+- [Indexing Module](../modules/indexing.md) - Full `FAISS` API reference- [Recognition Module](../modules/recognition.md) - Face recognition details-- [Batch Processing](batch-processing.md) - Process multiple files- [Video & Webcam](video-webcam.md) - Real-time processing- [Concepts: Thresholds](../concepts/thresholds-calibration.md) - Tuning similarity thresholdsdiff --git a/mkdocs.yml b/mkdocs.ymlindex 2cf57a1..ae7302e 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -153,6 +153,7 @@ nav:- Gaze: modules/gaze.md- Anti-Spoofing: modules/spoofing.md- Privacy: modules/privacy.md+ - Indexing: modules/indexing.md- Guides:- Overview: concepts/overview.md- Inputs & Outputs: concepts/inputs-outputs.mddiff --git a/tools/faiss_search.py b/tools/faiss_search.pynew file mode 100644index 0000000..81f6e21--- /dev/null+++ b/tools/faiss_search.py@@ -0,0 +1,208 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++"""FAISS index build and multi-identity face search.++Build a vector index from a directory of person sub-folders, then search+against it in a video or webcam stream.++Usage:+ python tools/faiss_search.py build --faces-dir dataset/ --db-path ./vector_index+ python tools/faiss_search.py run --db-path ./vector_index --source video.mp4+ python tools/faiss_search.py run --db-path ./vector_index --source 0 # webcam+"""++from __future__ import annotations++import argparse+import os+from pathlib import Path++from _common import IMAGE_EXTENSIONS, get_source_type+import cv2++from uniface import create_detector, create_recognizer+from uniface.draw import draw_corner_bbox, draw_text_label+from uniface.indexing import FAISS+++def _draw_face(image, bbox, text: str, color: tuple[int, int, int]) -> None:+ x1, y1, x2, y2 = map(int, bbox[:4])+ thickness = max(round(sum(image.shape[:2]) / 2 * 0.003), 2)+ font_scale = max(0.4, min(0.7, (y2 - y1) / 200))+ draw_corner_bbox(image, (x1, y1, x2, y2), color=color, thickness=thickness)+ draw_text_label(image, text, x1, y1, bg_color=color, font_scale=font_scale)+++def process_frame(frame, detector, recognizer, store: FAISS, threshold: float = 0.4):+ faces = detector.detect(frame)+ if not faces:+ return frame++ for face in faces:+ embedding = recognizer.get_normalized_embedding(frame, face.landmarks)+ result, sim = store.search(embedding, threshold=threshold)++ text = f'{result["person_id"]} ({sim:.2f})' if result else f'Unknown ({sim:.2f})'+ color = (0, 255, 0) if result else (0, 0, 255)+ _draw_face(frame, face.bbox, text, color)++ return frame+++def process_video(detector, recognizer, store: FAISS, video_path: str, save_dir: str, threshold: float = 0.4):+ cap = cv2.VideoCapture(video_path)+ if not cap.isOpened():+ print(f"Error: Cannot open video file '{video_path}'")+ return++ fps = cap.get(cv2.CAP_PROP_FPS)+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(video_path).stem}_faiss_search.mp4')+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))++ print(f'Processing video: {video_path} ({total_frames} frames)')+ frame_count = 0++ while True:+ ret, frame = cap.read()+ if not ret:+ break++ frame_count += 1+ frame = process_frame(frame, detector, recognizer, store, threshold)+ out.write(frame)++ if frame_count % 100 == 0:+ print(f' Processed {frame_count}/{total_frames} frames...')++ cap.release()+ out.release()+ print(f'Done! Output saved: {output_path}')+++def run_camera(detector, recognizer, store: FAISS, camera_id: int = 0, threshold: float = 0.4):+ cap = cv2.VideoCapture(camera_id)+ if not cap.isOpened():+ print(f'Cannot open camera {camera_id}')+ return++ print("Press 'q' to quit")++ while True:+ ret, frame = cap.read()+ frame = cv2.flip(frame, 1)+ if not ret:+ break++ frame = process_frame(frame, detector, recognizer, store, threshold)++ cv2.imshow('Vector Search', frame)+ if cv2.waitKey(1) & 0xFF == ord('q'):+ break++ cap.release()+ cv2.destroyAllWindows()+++def build(args: argparse.Namespace) -> None:+ faces_dir = Path(args.faces_dir)+ if not faces_dir.is_dir():+ print(f"Error: '{faces_dir}' is not a directory")+ return++ detector = create_detector()+ recognizer = create_recognizer()+ store = FAISS(db_path=args.db_path)++ persons = sorted(p.name for p in faces_dir.iterdir() if p.is_dir())+ if not persons:+ print(f"Error: No sub-folders found in '{faces_dir}'")+ return++ print(f'Found {len(persons)} persons: {", ".join(persons)}')++ total_added = 0+ for person_id in persons:+ person_dir = faces_dir / person_id+ images = [f for f in person_dir.iterdir() if f.suffix.lower() in IMAGE_EXTENSIONS]++ added = 0+ for img_path in images:+ image = cv2.imread(str(img_path))+ if image is None:+ print(f' Warning: Failed to read {img_path}, skipping')+ continue++ faces = detector.detect(image)+ if not faces:+ print(f' Warning: No face detected in {img_path}, skipping')+ continue++ embedding = recognizer.get_normalized_embedding(image, faces[0].landmarks)+ store.add(embedding, {'person_id': person_id, 'source': str(img_path)})+ added += 1++ total_added += added+ if added:+ print(f' {person_id}: {added} embeddings added')+ else:+ print(f' {person_id}: no valid faces found')++ store.save()+ print(f'\nIndex saved to {args.db_path} ({total_added} vectors, {len(persons)} persons)')+++def run(args: argparse.Namespace) -> None:+ detector = create_detector()+ recognizer = create_recognizer()++ store = FAISS(db_path=args.db_path)+ if not store.load():+ print(f"Error: No index found at '{args.db_path}'")+ return+ print(f'Loaded FAISS index: {store}')++ source_type = get_source_type(args.source)++ if source_type == 'camera':+ run_camera(detector, recognizer, store, int(args.source), args.threshold)+ elif source_type == 'video':+ if not os.path.exists(args.source):+ print(f'Error: Video not found: {args.source}')+ return+ process_video(detector, recognizer, store, args.source, args.save_dir, args.threshold)+ else:+ print(f"Error: Source must be a video file or camera ID, not '{args.source}'")+++def main():+ parser = argparse.ArgumentParser(description='FAISS vector search')+ sub = parser.add_subparsers(dest='command', required=True)++ build_p = sub.add_parser('build', help='Build a FAISS index from person sub-folders')+ build_p.add_argument('--faces-dir', type=str, required=True, help='Directory with person sub-folders')+ build_p.add_argument('--db-path', type=str, default='./vector_index', help='Where to save the index')++ run_p = sub.add_parser('run', help='Search faces against a FAISS index')+ run_p.add_argument('--db-path', type=str, required=True, help='Path to saved FAISS index')+ run_p.add_argument('--source', type=str, required=True, help='Video path or camera ID')+ run_p.add_argument('--threshold', type=float, default=0.4, help='Similarity threshold')+ run_p.add_argument('--save-dir', type=str, default='outputs', help='Output directory')++ args = parser.parse_args()++ if args.command == 'build':+ build(args)+ elif args.command == 'run':+ run(args)+++if __name__ == '__main__':+ main()diff --git a/tools/search.py b/tools/search.pyindex 45fd05a..b767d57 100644--- a/tools/search.py+++ b/tools/search.py@@ -2,11 +2,14 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-"""Real-time face search: match faces against a reference image.+"""Single-reference face search on video or webcam.++Given a reference face image, detects faces in the source and shows+whether each face matches the reference.Usage:- python tools/search.py --reference person.jpg --source 0 # webcam- python tools/search.py --reference person.jpg --source video.mp4+ python tools/search.py --reference ref.jpg --source video.mp4+ python tools/search.py --reference ref.jpg --source 0 # webcam"""from __future__ import annotations@@ -19,23 +22,12 @@ from _common import get_source_typeimport cv2import numpy as np-from uniface.detection import SCRFD, RetinaFace+from uniface import create_detector, create_recognizer+from uniface.draw import draw_corner_bbox, draw_text_labelfrom uniface.face_utils import compute_similarity-from uniface.recognition import ArcFace, MobileFace, SphereFace---def get_recognizer(name: str):- """Get recognizer by name."""- if name == 'arcface':- return ArcFace()- elif name == 'mobileface':- return MobileFace()- else:- return SphereFace()def extract_reference_embedding(detector, recognizer, image_path: str) -> np.ndarray:- """Extract embedding from reference image."""image = cv2.imread(image_path)if image is None:raise RuntimeError(f'Failed to load image: {image_path}')@@ -44,33 +36,34 @@ def extract_reference_embedding(detector, recognizer, image_path: str) -> np.ndaif not faces:raise RuntimeError('No faces found in reference image.')- landmarks = faces[0].landmarks- return recognizer.get_normalized_embedding(image, landmarks)+ return recognizer.get_normalized_embedding(image, faces[0].landmarks)+++def _draw_face(image, bbox, text: str, color: tuple[int, int, int]) -> None:+ x1, y1, x2, y2 = map(int, bbox[:4])+ thickness = max(round(sum(image.shape[:2]) / 2 * 0.003), 2)+ font_scale = max(0.4, min(0.7, (y2 - y1) / 200))+ draw_corner_bbox(image, (x1, y1, x2, y2), color=color, thickness=thickness)+ draw_text_label(image, text, x1, y1, bg_color=color, font_scale=font_scale)def process_frame(frame, detector, recognizer, ref_embedding: np.ndarray, threshold: float = 0.4):- """Process a single frame and return annotated frame."""faces = detector.detect(frame)for face in faces:- bbox = face.bbox- landmarks = face.landmarks- x1, y1, x2, y2 = map(int, bbox)-- embedding = recognizer.get_normalized_embedding(frame, landmarks)+ embedding = recognizer.get_normalized_embedding(frame, face.landmarks)sim = compute_similarity(ref_embedding, embedding)- label = f'Match ({sim:.2f})' if sim > threshold else f'Unknown ({sim:.2f})'+ text = f'Match ({sim:.2f})' if sim > threshold else f'Unknown ({sim:.2f})'color = (0, 255, 0) if sim > threshold else (0, 0, 255)-- cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)- cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)+ _draw_face(frame, face.bbox, text, color)return frame-def process_video(detector, recognizer, ref_embedding: np.ndarray, video_path: str, save_dir: str, threshold: float):- """Process a video file."""+def process_video(+ detector, recognizer, video_path: str, save_dir: str, ref_embedding: np.ndarray, threshold: float = 0.4+):cap = cv2.VideoCapture(video_path)if not cap.isOpened():print(f"Error: Cannot open video file '{video_path}'")@@ -107,7 +100,6 @@ def process_video(detector, recognizer, ref_embedding: np.ndarray, video_path: sdef run_camera(detector, recognizer, ref_embedding: np.ndarray, camera_id: int = 0, threshold: float = 0.4):- """Run real-time face search on webcam."""cap = cv2.VideoCapture(camera_id)if not cap.isOpened():print(f'Cannot open camera {camera_id}')@@ -123,7 +115,7 @@ def run_camera(detector, recognizer, ref_embedding: np.ndarray, camera_id: int =frame = process_frame(frame, detector, recognizer, ref_embedding, threshold)- cv2.imshow('Face Recognition', frame)+ cv2.imshow('Face Search', frame)if cv2.waitKey(1) & 0xFF == ord('q'):break@@ -132,17 +124,10 @@ def run_camera(detector, recognizer, ref_embedding: np.ndarray, camera_id: int =def main():- parser = argparse.ArgumentParser(description='Face search using a reference image')+ parser = argparse.ArgumentParser(description='Single-reference face search')parser.add_argument('--reference', type=str, required=True, help='Reference face image')- parser.add_argument('--source', type=str, required=True, help='Video path or camera ID (0, 1, ...)')- parser.add_argument('--threshold', type=float, default=0.4, help='Match threshold')- parser.add_argument('--detector', type=str, default='scrfd', choices=['retinaface', 'scrfd'])- parser.add_argument(- '--recognizer',- type=str,- default='arcface',- choices=['arcface', 'mobileface', 'sphereface'],- )+ parser.add_argument('--source', type=str, required=True, help='Video path or camera ID')+ parser.add_argument('--threshold', type=float, default=0.4, help='Similarity threshold')parser.add_argument('--save-dir', type=str, default='outputs', help='Output directory')args = parser.parse_args()@@ -150,8 +135,8 @@ def main():print(f'Error: Reference image not found: {args.reference}')return- detector = RetinaFace() if args.detector == 'retinaface' else SCRFD()- recognizer = get_recognizer(args.recognizer)+ detector = create_detector()+ recognizer = create_recognizer()print(f'Loading reference: {args.reference}')ref_embedding = extract_reference_embedding(detector, recognizer, args.reference)@@ -164,10 +149,9 @@ def main():if not os.path.exists(args.source):print(f'Error: Video not found: {args.source}')return- process_video(detector, recognizer, ref_embedding, args.source, args.save_dir, args.threshold)+ process_video(detector, recognizer, args.source, args.save_dir, ref_embedding, args.threshold)else:print(f"Error: Source must be a video file or camera ID, not '{args.source}'")- print('Supported formats: videos (.mp4, .avi, ...) or camera ID (0, 1, ...)')if __name__ == '__main__':diff --git a/uniface/__init__.py b/uniface/__init__.pyindex d67ae7f..41897f8 100644--- a/uniface/__init__.py+++ b/uniface/__init__.py@@ -31,6 +31,8 @@ __license__ = 'MIT'__author__ = 'Yakhyokhuja Valikhujaev'__version__ = '3.0.0'+import contextlib+from uniface.face_utils import compute_similarity, face_alignmentfrom uniface.log import Logger, enable_loggingfrom uniface.model_store import download_models, get_cache_dir, set_cache_dir, verify_model_weights@@ -54,6 +56,10 @@ from .spoofing import MiniFASNet, create_spooferfrom .tracking import BYTETrackerfrom .types import AttributeResult, EmotionResult, Face, GazeResult, SpoofingResult+# Optional: FAISS vector store (requires `pip install faiss-cpu`)+with contextlib.suppress(ImportError):+ from .indexing import FAISS+__all__ = [# Metadata'__author__',@@ -101,6 +107,8 @@ __all__ = ['BYTETracker',# Privacy'BlurFace',+ # Indexing (optional)+ 'FAISS',# Utilities'Logger','compute_similarity',diff --git a/uniface/indexing/__init__.py b/uniface/indexing/__init__.pynew file mode 100644index 0000000..c0fef16--- /dev/null+++ b/uniface/indexing/__init__.py@@ -0,0 +1,9 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++"""Vector indexing backends for fast similarity search."""++from uniface.indexing.faiss import FAISS++__all__ = ['FAISS']diff --git a/uniface/indexing/faiss.py b/uniface/indexing/faiss.pynew file mode 100644index 0000000..6552ab8--- /dev/null+++ b/uniface/indexing/faiss.py@@ -0,0 +1,197 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++import json+import os+from typing import Any++import numpy as np++from uniface.log import Logger++__all__ = ['FAISS']++Metadata = dict[str, Any]+++def _import_faiss():+ """Lazily import faiss, raising a clear error if not installed."""+ # Prevent OpenMP abort on macOS when multiple libraries (e.g. scipy,+ # torch) each bundle their own libomp.+ os.environ.setdefault('KMP_DUPLICATE_LIB_OK', 'TRUE')++ try:+ import faiss+ except ImportError as exc:+ raise ImportError(+ 'faiss is required for FAISS vector store. '+ 'Install it with: pip install faiss-cpu (CPU) '+ 'or: pip install faiss-gpu (CUDA)'+ ) from exc+ return faiss+++class FAISS:+ """FAISS vector store using IndexFlatIP (inner product).++ Vectors must be L2-normalised **before** being added so that inner+ product equals cosine similarity. The store does not normalise+ internally -- that is the caller's responsibility.++ Each vector is paired with a metadata dict that can carry any+ JSON-serialisable payload (person ID, name, source image, etc.).++ Args:+ embedding_size: Dimension of embedding vectors.+ db_path: Directory for persisting the index and metadata.++ Example:+ >>> from uniface.indexing import FAISS+ >>> store = FAISS(embedding_size=512, db_path='./my_index')+ >>> store.add(embedding, {'person_id': '001', 'name': 'Alice'})+ >>> result, score = store.search(query_embedding)+ >>> result['name']+ 'Alice'+ """++ def __init__(+ self,+ embedding_size: int = 512,+ db_path: str = './vector_index',+ ) -> None:+ faiss = _import_faiss()++ self.embedding_size = embedding_size+ self.db_path = db_path+ self._index_file = os.path.join(db_path, 'faiss_index.bin')+ self._meta_file = os.path.join(db_path, 'metadata.json')++ os.makedirs(db_path, exist_ok=True)++ self.index = faiss.IndexFlatIP(embedding_size)+ self.metadata: list[Metadata] = []++ def add(self, embedding: np.ndarray, metadata: Metadata) -> None:+ """Add a single embedding with associated metadata.++ Args:+ embedding: Embedding vector (must be L2-normalised).+ metadata: Arbitrary dict of JSON-serialisable key-value pairs.+ """+ vec = self._prepare(embedding).reshape(1, -1)+ self.index.add(vec)+ self.metadata.append(metadata)++ def search(+ self,+ embedding: np.ndarray,+ threshold: float = 0.4,+ ) -> tuple[Metadata | None, float]:+ """Find the closest match for a query embedding.++ Args:+ embedding: Query embedding vector (must be L2-normalised).+ threshold: Minimum cosine similarity to accept a match.++ Returns:+ ``(metadata, similarity)`` for the best match, or+ ``(None, similarity)`` when below *threshold* or the+ index is empty.+ """+ if self.index.ntotal == 0:+ return None, 0.0++ vec = self._prepare(embedding).reshape(1, -1)+ similarities, indices = self.index.search(vec, 1)++ similarity = float(similarities[0][0])+ idx = int(indices[0][0])++ if similarity > threshold and 0 <= idx < len(self.metadata):+ return self.metadata[idx], similarity+ return None, similarity++ def remove(self, key: str, value: Any) -> int:+ """Remove all entries where ``metadata[key] == value`` and rebuild.++ Args:+ key: Metadata key to match against.+ value: Value to match.++ Returns:+ Number of entries removed.+ """+ faiss = _import_faiss()++ keep = [i for i, m in enumerate(self.metadata) if m.get(key) != value]+ removed = len(self.metadata) - len(keep)+ if removed == 0:+ return 0++ if keep:+ vectors = np.empty((len(keep), self.embedding_size), dtype=np.float32)+ for dst, src in enumerate(keep):+ self.index.reconstruct(src, vectors[dst])+ new_index = faiss.IndexFlatIP(self.embedding_size)+ new_index.add(vectors)+ else:+ new_index = faiss.IndexFlatIP(self.embedding_size)++ self.index = new_index+ self.metadata = [self.metadata[i] for i in keep]+ Logger.info('Removed %d entries where %s=%s (%d remaining)', removed, key, value, self.index.ntotal)+ return removed++ def save(self) -> None:+ """Persist the FAISS index and metadata to disk."""+ faiss = _import_faiss()++ faiss.write_index(self.index, self._index_file)+ with open(self._meta_file, 'w', encoding='utf-8') as fh:+ json.dump(self.metadata, fh, ensure_ascii=False, indent=2)+ Logger.info('Saved FAISS index with %d vectors to %s', self.index.ntotal, self.db_path)++ def load(self) -> bool:+ """Load a previously saved index and metadata from disk.++ Returns:+ ``True`` if loaded successfully, ``False`` if files are missing.++ Raises:+ RuntimeError: If files exist but cannot be read.+ """+ if not (os.path.exists(self._index_file) and os.path.exists(self._meta_file)):+ return False++ faiss = _import_faiss()++ try:+ loaded_index = faiss.read_index(self._index_file)+ with open(self._meta_file, encoding='utf-8') as fh:+ loaded_metadata: list[Metadata] = json.load(fh)+ except Exception as exc:+ raise RuntimeError(f'Failed to load FAISS index from {self.db_path}') from exc++ self.index = loaded_index+ self.metadata = loaded_metadata+ Logger.info('Loaded FAISS index with %d vectors from %s', self.index.ntotal, self.db_path)+ return True++ @property+ def size(self) -> int:+ """Number of vectors currently in the index."""+ return self.index.ntotal++ @staticmethod+ def _prepare(vec: np.ndarray) -> np.ndarray:+ """Cast to contiguous float32 for FAISS compatibility."""+ return np.ascontiguousarray(vec.ravel(), dtype=np.float32)++ def __len__(self) -> int:+ return self.index.ntotal++ def __repr__(self) -> str:+ return f'FAISS(embedding_size={self.embedding_size}, vectors={self.index.ntotal})'diff --git a/uniface/privacy/blur.py b/uniface/privacy/blur.pyindex 0931b55..936ad50 100644--- a/uniface/privacy/blur.py+++ b/uniface/privacy/blur.py@@ -4,14 +4,11 @@from __future__ import annotations-from typing import TYPE_CHECKING, ClassVar+from typing import ClassVarimport cv2import numpy as np-if TYPE_CHECKING:- pass-__all__ = ['BlurFace', 'EllipticalBlur']