File size: 5,042 Bytes
194469b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | """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
@property
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
|