Download database.py from Atomio/facerecog: direct link, hf CLI and curl.
- Browser
- Download file 5.04 kB
-
https://huggingface.co/spaces/Atomio/facerecog/resolve/main/database.py
- Command line
-
hf download hf://spaces/Atomio/facerecog/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Atomio/facerecog/resolve/main/database.py
5.04 kB
| """Database connection and configuration.""" | |
| import logging | |
| from typing import Any | |
| from supabase import Client, create_client | |
| from config import settings | |
| logger = logging.getLogger(__name__) | |
| class SupabaseClient: | |
| """Supabase client wrapper with connection management.""" | |
| def __init__(self) -> None: | |
| self._client: Client | None = None | |
| def client(self) -> Client: | |
| """Get or create Supabase client.""" | |
| if self._client is None: | |
| self._client = create_client( | |
| supabase_url=settings.SUPABASE_URL, | |
| supabase_key=settings.SUPABASE_SERVICE_ROLE_KEY, | |
| ) | |
| logger.info("Supabase client initialized") | |
| return self._client | |
| async def health_check(self) -> bool: | |
| """Check if Supabase connection is healthy.""" | |
| try: | |
| # Simple query to test connection | |
| result = self.client.table("faces").select("count", count="exact").execute() | |
| return result is not None | |
| except Exception as e: | |
| logger.error(f"Supabase health check failed: {e}") | |
| return False | |
| async def insert_face_embedding( | |
| self, user_id: str, embedding: list[float] | |
| ) -> dict[str, Any]: | |
| """Insert a face embedding into the database.""" | |
| try: | |
| result = ( | |
| self.client.table("faces") | |
| .insert({"user_id": user_id, "embedding": embedding}) | |
| .execute() | |
| ) | |
| if result.data: | |
| logger.info(f"Face embedding inserted for user: {user_id}") | |
| return result.data[0] | |
| else: | |
| raise Exception("No data returned from insert operation") | |
| except Exception as e: | |
| logger.error(f"Failed to insert face embedding: {e}") | |
| raise | |
| async def search_similar_faces( | |
| self, embedding: list[float], threshold: float = 0.6, limit: int = 5 | |
| ) -> list[dict[str, Any]]: | |
| """Search for similar face embeddings using vector similarity.""" | |
| try: | |
| # Use RPC function for vector similarity search | |
| result = ( | |
| self.client.rpc( | |
| "search_similar_faces", | |
| { | |
| "query_embedding": embedding, | |
| "similarity_threshold": threshold, | |
| "match_count": limit, | |
| }, | |
| ) | |
| .execute() | |
| ) | |
| if result.data: | |
| logger.info(f"Found {len(result.data)} similar faces") | |
| return result.data | |
| else: | |
| logger.info("No similar faces found") | |
| return [] | |
| except Exception as e: | |
| logger.error(f"Failed to search similar faces: {e}") | |
| raise | |
| async def get_user_faces(self, user_id: str) -> list[dict[str, Any]]: | |
| """Get all face embeddings for a specific user.""" | |
| try: | |
| result = ( | |
| self.client.table("faces") | |
| .select("*") | |
| .eq("user_id", user_id) | |
| .execute() | |
| ) | |
| if result.data: | |
| logger.info(f"Found {len(result.data)} faces for user: {user_id}") | |
| return result.data | |
| else: | |
| logger.info(f"No faces found for user: {user_id}") | |
| return [] | |
| except Exception as e: | |
| logger.error(f"Failed to get user faces: {e}") | |
| raise | |
| async def delete_user_faces(self, user_id: str) -> bool: | |
| """Delete all face embeddings for a specific user.""" | |
| try: | |
| ( | |
| self.client.table("faces") | |
| .delete() | |
| .eq("user_id", user_id) | |
| .execute() | |
| ) | |
| logger.info(f"Deleted faces for user: {user_id}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to delete user faces: {e}") | |
| raise | |
| async def get_face_by_id(self, face_id: str) -> dict[str, Any] | None: | |
| """Get a specific face embedding by ID.""" | |
| try: | |
| result = ( | |
| self.client.table("faces") | |
| .select("*") | |
| .eq("id", face_id) | |
| .single() | |
| .execute() | |
| ) | |
| if result.data: | |
| logger.info(f"Found face with ID: {face_id}") | |
| return result.data | |
| else: | |
| logger.info(f"No face found with ID: {face_id}") | |
| return None | |
| except Exception as e: | |
| logger.error(f"Failed to get face by ID: {e}") | |
| raise | |
| # Global Supabase client instance | |
| supabase_client = SupabaseClient() | |
| async def get_database() -> SupabaseClient: | |
| """Dependency to get database client.""" | |
| return supabase_client | |