|
| 1 | +# built-in dependencies |
| 2 | +import os |
| 3 | +import json |
| 4 | +import hashlib |
| 5 | +import struct |
| 6 | +import math |
| 7 | +from typing import Any, Dict, Optional, List, Union |
| 8 | + |
| 9 | +# project dependencies |
| 10 | +from deepface.modules.database.types import Database |
| 11 | +from deepface.modules.modeling import build_model |
| 12 | +from deepface.commons.logger import Logger |
| 13 | + |
| 14 | +logger = Logger() |
| 15 | + |
| 16 | + |
| 17 | +class PineconeClient(Database): |
| 18 | + """ |
| 19 | + Pinecone client for storing and retrieving face embeddings and indices. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + connection_details: Optional[Union[str, Dict[str, Any]]] = None, |
| 25 | + connection: Any = None, |
| 26 | + ): |
| 27 | + try: |
| 28 | + from pinecone import Pinecone, ServerlessSpec |
| 29 | + except (ModuleNotFoundError, ImportError) as e: |
| 30 | + raise ValueError( |
| 31 | + "pinecone is an optional dependency. Install with 'pip install pinecone'" |
| 32 | + ) from e |
| 33 | + |
| 34 | + self.pinecone = Pinecone |
| 35 | + self.serverless_spec = ServerlessSpec |
| 36 | + |
| 37 | + if connection is not None: |
| 38 | + self.client = connection |
| 39 | + else: |
| 40 | + self.conn_details = connection_details or os.environ.get("DEEPFACE_PINECONE_API_KEY") |
| 41 | + if not isinstance(self.conn_details, str): |
| 42 | + raise ValueError( |
| 43 | + "Pinecone api key must be provided as a string in connection_details " |
| 44 | + "or via DEEPFACE_PINECONE_API_KEY environment variable." |
| 45 | + ) |
| 46 | + |
| 47 | + self.client = self.pinecone(api_key=self.conn_details) |
| 48 | + |
| 49 | + def initialize_database(self, **kwargs: Any) -> None: |
| 50 | + """ |
| 51 | + Ensure Pinecone index exists. |
| 52 | + """ |
| 53 | + model_name = kwargs.get("model_name", "VGG-Face") |
| 54 | + detector_backend = kwargs.get("detector_backend", "opencv") |
| 55 | + aligned = kwargs.get("aligned", True) |
| 56 | + l2_normalized = kwargs.get("l2_normalized", False) |
| 57 | + |
| 58 | + index_name = self.__generate_index_name( |
| 59 | + model_name, detector_backend, aligned, l2_normalized |
| 60 | + ) |
| 61 | + |
| 62 | + if self.client.has_index(index_name): |
| 63 | + logger.debug(f"Pinecone index '{index_name}' already exists.") |
| 64 | + return |
| 65 | + |
| 66 | + model = build_model(task="facial_recognition", model_name=model_name) |
| 67 | + dimensions = model.output_shape |
| 68 | + similarity_function = "cosine" if l2_normalized else "euclidean" |
| 69 | + |
| 70 | + self.client.create_index( |
| 71 | + name=index_name, |
| 72 | + dimension=dimensions, |
| 73 | + metric=similarity_function, |
| 74 | + spec=self.serverless_spec( |
| 75 | + cloud=os.getenv("DEEPFACE_PINECONE_CLOUD", "aws"), |
| 76 | + region=os.getenv("DEEPFACE_PINECONE_REGION", "us-east-1"), |
| 77 | + ), |
| 78 | + ) |
| 79 | + logger.debug(f"Created Pinecone index '{index_name}' with dimension {dimensions}.") |
| 80 | + |
| 81 | + def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: |
| 82 | + """ |
| 83 | + Insert embeddings into Pinecone database in batches. |
| 84 | + """ |
| 85 | + if not embeddings: |
| 86 | + raise ValueError("No embeddings to insert.") |
| 87 | + |
| 88 | + self.initialize_database( |
| 89 | + model_name=embeddings[0]["model_name"], |
| 90 | + detector_backend=embeddings[0]["detector_backend"], |
| 91 | + aligned=embeddings[0]["aligned"], |
| 92 | + l2_normalized=embeddings[0]["l2_normalized"], |
| 93 | + ) |
| 94 | + |
| 95 | + index_name = self.__generate_index_name( |
| 96 | + embeddings[0]["model_name"], |
| 97 | + embeddings[0]["detector_backend"], |
| 98 | + embeddings[0]["aligned"], |
| 99 | + embeddings[0]["l2_normalized"], |
| 100 | + ) |
| 101 | + |
| 102 | + # connect to the index |
| 103 | + index = self.client.Index(index_name) |
| 104 | + |
| 105 | + total = 0 |
| 106 | + for i in range(0, len(embeddings), batch_size): |
| 107 | + batch = embeddings[i : i + batch_size] |
| 108 | + vectors = [] |
| 109 | + for e in batch: |
| 110 | + face_json = json.dumps(e["face"].tolist()) |
| 111 | + face_hash = hashlib.sha256(face_json.encode()).hexdigest() |
| 112 | + embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) |
| 113 | + embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() |
| 114 | + |
| 115 | + vectors.append( |
| 116 | + { |
| 117 | + "id": f"{face_hash}:{embedding_hash}", |
| 118 | + "values": e["embedding"], |
| 119 | + "metadata": { |
| 120 | + "img_name": e["img_name"], |
| 121 | + # "face": e["face"].tolist(), |
| 122 | + # "face_shape": list(e["face"].shape), |
| 123 | + }, |
| 124 | + } |
| 125 | + ) |
| 126 | + index.upsert(vectors=vectors) |
| 127 | + total += len(vectors) |
| 128 | + |
| 129 | + return total |
| 130 | + |
| 131 | + def search_by_vector( |
| 132 | + self, |
| 133 | + vector: List[float], |
| 134 | + model_name: str = "VGG-Face", |
| 135 | + detector_backend: str = "opencv", |
| 136 | + aligned: bool = True, |
| 137 | + l2_normalized: bool = False, |
| 138 | + limit: int = 10, |
| 139 | + ) -> List[Dict[str, Any]]: |
| 140 | + """ |
| 141 | + ANN search using the main vector (embedding). |
| 142 | + """ |
| 143 | + out: List[Dict[str, Any]] = [] |
| 144 | + |
| 145 | + self.initialize_database( |
| 146 | + model_name=model_name, |
| 147 | + detector_backend=detector_backend, |
| 148 | + aligned=aligned, |
| 149 | + l2_normalized=l2_normalized, |
| 150 | + ) |
| 151 | + |
| 152 | + index_name = self.__generate_index_name( |
| 153 | + model_name, detector_backend, aligned, l2_normalized |
| 154 | + ) |
| 155 | + |
| 156 | + index = self.client.Index(index_name) |
| 157 | + results = index.query( |
| 158 | + vector=vector, |
| 159 | + top_k=limit, |
| 160 | + include_metadata=True, |
| 161 | + include_values=False, |
| 162 | + ) |
| 163 | + |
| 164 | + if not results.matches: |
| 165 | + return out |
| 166 | + |
| 167 | + for res in results.matches: |
| 168 | + score = float(res.score) |
| 169 | + if l2_normalized: |
| 170 | + distance = 1 - score |
| 171 | + else: |
| 172 | + distance = math.sqrt(max(score, 0.0)) |
| 173 | + |
| 174 | + out.append( |
| 175 | + { |
| 176 | + "id": res.id, |
| 177 | + "distance": distance, |
| 178 | + "img_name": res.metadata.get("img_name"), |
| 179 | + } |
| 180 | + ) |
| 181 | + return out |
| 182 | + |
| 183 | + def fetch_all_embeddings( |
| 184 | + self, |
| 185 | + model_name: str, |
| 186 | + detector_backend: str, |
| 187 | + aligned: bool, |
| 188 | + l2_normalized: bool, |
| 189 | + batch_size: int = 1000, |
| 190 | + ) -> List[Dict[str, Any]]: |
| 191 | + """ |
| 192 | + Fetch all embeddings from Pinecone database in batches. |
| 193 | + """ |
| 194 | + out: List[Dict[str, Any]] = [] |
| 195 | + |
| 196 | + self.initialize_database( |
| 197 | + model_name=model_name, |
| 198 | + detector_backend=detector_backend, |
| 199 | + aligned=aligned, |
| 200 | + l2_normalized=l2_normalized, |
| 201 | + ) |
| 202 | + |
| 203 | + index_name = self.__generate_index_name( |
| 204 | + model_name, detector_backend, aligned, l2_normalized |
| 205 | + ) |
| 206 | + |
| 207 | + index = self.client.Index(index_name) |
| 208 | + |
| 209 | + # Fetch all IDs |
| 210 | + ids: List[str] = [] |
| 211 | + for _id in index.list(): |
| 212 | + ids.extend(_id) |
| 213 | + |
| 214 | + for i in range(0, len(ids), batch_size): |
| 215 | + batch_ids = ids[i : i + batch_size] |
| 216 | + fetched = index.fetch(ids=batch_ids) |
| 217 | + for _id, v in fetched.get("vectors", {}).items(): |
| 218 | + md = v.get("metadata") or {} |
| 219 | + out.append( |
| 220 | + { |
| 221 | + "id": _id, |
| 222 | + "embedding": v.get("values"), |
| 223 | + "img_name": md.get("img_name"), |
| 224 | + "face_hash": md.get("face_hash"), |
| 225 | + "embedding_hash": md.get("embedding_hash"), |
| 226 | + } |
| 227 | + ) |
| 228 | + |
| 229 | + return out |
| 230 | + |
| 231 | + def close(self) -> None: |
| 232 | + """Pinecone client does not require explicit closure""" |
| 233 | + return |
| 234 | + |
| 235 | + @staticmethod |
| 236 | + def __generate_index_name( |
| 237 | + model_name: str, |
| 238 | + detector_backend: str, |
| 239 | + aligned: bool, |
| 240 | + l2_normalized: bool, |
| 241 | + ) -> str: |
| 242 | + """ |
| 243 | + Generate Pinecone index name based on parameters. |
| 244 | + """ |
| 245 | + index_name_attributes = [ |
| 246 | + "embeddings", |
| 247 | + model_name.replace("-", ""), |
| 248 | + detector_backend, |
| 249 | + "Aligned" if aligned else "Unaligned", |
| 250 | + "Norm" if l2_normalized else "Raw", |
| 251 | + ] |
| 252 | + return "-".join(index_name_attributes).lower() |
0 commit comments